JDBC

JDBC

JDBC六步

  • 注册驱动

  • 建立连接

  • 获取预编译的数据库操作对象

  • 执行SQL

  • 处理查询结果

  • 释放资源

 Connection conn = null;
PrepareStatement ps = null;
ResultSet rs = null;

String url="jdbc:mysql://数据库地址:端口号/数据库名称";
String user="用户名";
String pwd="密码";

try{
//注册驱动
Class.forname("com.mysql.cj.jdbc.Driver")
//建立连接
conn = DriverManager.getConnection(url,user,pwd);
//获取预编译的数据库操作对象
String SQL="select * from table";
ps = conn.PrepareStatement(SQL);
//执行SQL
rs = ps.executeQuery();
//处理查询结果
while(rs.next()){
String name = rs.getString("name");
}
}catch(Exception e){
e.printStackTrace()
}finally{
//释放资源
if(rs!=null){
try{
rs.close();
}catch(Exception e){
e.printStackTrace()
}
}
if(ps!=null){
try{
ps.close();
}catch(Exception e){
e.printStackTrace()
}
}
if(conn!=null){
try{
conn.close();
}catch(Exception e){
e.printStackTrace()
}
}
}

标签: Java

添加新评论