老师,作业求建议

来源:3-4 自由编程

梨海

2020-07-18 16:32:15

package com.jdbc.demo3;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;


import org.junit.Test;


public class JDBCDemo3 {

@Test

public void demo1() {

Connection con=null;

PreparedStatement ps=null;

try {

//            加载驱动

Class.forName("com.mysql.jdbc.Driver");

// 获得连接

con=DriverManager.getConnection("jdbc:mysql:///jdbctest?serverTimezone=Hongkong","root","12345");

String sql="update goods set price=4000 where id='1'";

// 获得对象

ps=con.prepareStatement(sql);

// 执行sql语句---更新

int i=ps.executeUpdate(sql);

// 结果处理

if(i>0) {

// 成功

System.out.println("修改成功");

System.out.println("=========");

// 在成功的前提下执行遍历

String sql1="select * from goods";

ps=con.prepareStatement(sql1);

ResultSet result=ps.executeQuery(sql1);

while(result.next()) {

int id=result.getInt("id");

String name=result.getString("name");

float price=result.getFloat("price");

String desp=result.getString("desp");

System.out.println(id+" "+name+' '+price+' '+desp);

System.out.println("=========");

}

}else {

// 失败

System.out.println("修改失败了!!!");

}

} catch (Exception e) {

e.printStackTrace();

}finally {

// 释放连接

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

ps = null;

}

if (con != null) {

try {

con.close();

} catch (SQLException e) {

e.printStackTrace();

}

con = null;

}

}

}

}

写回答

1回答

好帮手慕小班

2020-07-18

同学写的不错哦,符合作业要求,继续加油!!!

如果我的回答解决了你的疑问,请采纳,祝学习愉快。

0

0 学习 · 8016 问题

查看课程