JDBC访问数据常用类和接口
DriverManager :管理JDBC驱动
Connection :连接数据库并传送数据
Statement :负责执行SQL语句
ResultSet:负责保存Statement执行后所产生的查询结果
JDBC访问数据库的步骤
加载JDBC驱动
与数据库建立连接
创建Statement或PreparedStatement对象
发送SQL语句,并得到返回结果
处理返回结果
释放资源
注意事项
遍历结果集中数据可使用列号或列名标识列
PreparedStatement比Statement提高了代码的安全性、可读性和可维护性
Statement常用方法:
ResultSet常用方法:
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(); | |
} | |
} | |
} | |
} |