在JDBC进阶1中建立了一个很简单的增删改查的代码,但是不能显示操作之后的变化,因此在此版本中对上一版本进行改进。
在MYSQL中建立如下如图所示的字段,然后添加值
image.png
image.png
将查询的while循环加入到子函数中:
image.png
完整代码如下:
import java.sql.*;
import java.util.Date;
public class renewal {
static Connection con;
static PreparedStatement sql;
static ResultSet res;
static int res1;
@SuppressWarnings("deprecation")
public static void main(String[] args) {
// TODO Auto-generated method stub
renewal c = new renewal();
con = c.getConnection();
System.out.println("原始数据:");
System.out.println("--------------------------");
query(con);
System.out.println("--------------------------");
try{
System.out.println("执行添加后:");
sql = con.prepareStatement("insert into stu(name,sex,birthday) values(?,?,?)"); //这里总是报错,说是参数个数不一致
//sql.setInt(1, 8);
sql.setString(1, "jenny");
sql.setInt(2, 1);
sql.setDate(3, new java.sql.Date(100));
sql.executeUpdate(); //update时是没有返回值的,所以不能赋值给res然后循环输出
System.out.println("--------------------------");
query(con);
System.out.println("--------------------------");
System.out.println("执行更新后:");
sql = con.prepareStatement("update stu set birthday =? where id =4");
sql.setString(1, "1990-00-00");
sql.executeUpdate();
System.out.println("--------------------------");
query(con);
System.out.println("--------------------------");
System.out.println("执行删除后:");
sql = con.prepareStatement("delete from stu where id =?");
sql.setInt(1,3);
sql.executeUpdate();
System.out.println("--------------------------");
query(con);
System.out.println("--------------------------");
}catch(Exception e){
e.printStackTrace();
}
}
public static void query(Connection con){
try {
sql = con.prepareStatement("select * from stu ");
res = sql.executeQuery(); //只有在Query的时才有返回值
while(res.next()){
String id = res.getString(1);
String name = res.getString("name");
String sex = res.getString("sex");
String birthday = res.getString("birthday");
System.out.print("编号:"+id);
System.out.print("姓名:"+name);
System.out.print("性别:"+sex);
System.out.println("生日:"+birthday);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:"+"//localhost/tysql?useSSL=false","root","12345678");
}catch(Exception e){
e.printStackTrace();
}
return con;
}
}
最后显示结果如图:
image.png
网友评论