JDBC链接

Java
456
0
0
2022-11-15
标签   Java基础

JDBC访问数据常用类和接口

img

DriverManager :管理JDBC驱动

Connection :连接数据库并传送数据

Statement :负责执行SQL语句

ResultSet:负责保存Statement执行后所产生的查询结果

JDBC访问数据库的步骤

加载JDBC驱动

与数据库建立连接

创建Statement或PreparedStatement对象

发送SQL语句,并得到返回结果

处理返回结果

释放资源

注意事项

遍历结果集中数据可使用列号或列名标识列

PreparedStatement比Statement提高了代码的安全性、可读性和可维护性

Statement常用方法:

img

ResultSet常用方法:

img

@Test
public void testxiugaiMaster() throws Exception{
Connection conn=null;
Statement stmr = null;
String name1="王五";
String password = "12345";
int money =100;
int count = 0;
int id=1;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.创建连接
try {
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/ebet","root","123");
System.out.println("打开数据连接");
String sql = "update master set name= '"+name1+"'"+",password='"+password+"'where id='"+id+"'";
stmr = conn.createStatement();
count=stmr.executeUpdate(sql);
if(count>0){
System.out.println("添加成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(conn!=null){
try {
conn.close();
System.out.println("关闭数据连接");
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmr!=null){
try {
stmr.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}