JDBC常用代码

时间:2023-03-08 16:25:50
JDBC常用代码
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/test";
//通过DriverManager获取连接
Connection conn=DriverManager.getConnection(url,"root","hello");
System.out.println("conn:"+conn);
//准备操作数据库
//Statement:用于执行静态SQL语句并返回它所生产结果的对象
Statement stm=conn.createStatement();
String sql="insert into test.new_table(t1,t2) values('t11','t22');";
Boolean ret =stm.execute(sql);
conn.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
package com.wzh.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement; /*
* 连接工厂
* 从面向对象的角度来说,凡是连接相关操作都给这个对象处理
*/
public class ConnectionFactory { private static final String URL="jdbc:mysql://127.0.0.1:3306/test";
private static final String USER="root";
private static final String PASSWORD="hello";
private static final String DRIVER="com.mysql.jdbc.Driver"; /**
* 获取数据库连接
* @return 成功返回 java.sql.Connection
* 失败返回NULL
* */
public static Connection GetConnection(){
try {
Class.forName(DRIVER);
return DriverManager.getConnection(URL,USER,PASSWORD);
} catch (Exception e) {
System.out.println("%%%%%%%%%%%% 获取连接错误 %%%%%%%%%%%%%%");
e.printStackTrace();
return null;
}
} /**
* 关闭数据库资源
* @param conn
* @param stm
* @param rs
*/
public static void Close(Connection conn,Statement stm,ResultSet rs)
{
try {
if(conn!=null) conn.close();
if(stm!=null) stm.close();
if(rs!=null) rs.close();
} catch (Exception e) {
System.out.println("%%%%%%%%%%%% 关闭连接错误 %%%%%%%%%%%%%%");
e.printStackTrace();
} }
}

  

PreparedStatement 用法:
Connection conn=null;
PreparedStatement stm=null;
ResultSet rs=null;
try {
//加载驱动
conn= ConnectionFactory.GetConnection();
System.out.println("conn:"+conn);
//准备操作数据库
//Statement:用于执行静态SQL语句并返回它所生产结果的对象
String sql="select * from new_table where t1=? and t2=?";
stm=conn.prepareStatement(sql);
stm.setString(, "");
stm.setString(, "aa");
System.out.println("sql:"+sql);
rs =stm.executeQuery(); while(rs.next()){
System.out.println(rs.getString("t1"));
System.out.println(rs.getBoolean("boo"));
}
System.out.println(rs);
conn.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
ConnectionFactory.Close(conn, stm, rs);
}
Statement 用法:
Connection conn=null;
Statement stm=null;
ResultSet rs=null;
try {
//加载驱动 conn= ConnectionFactory.GetConnection();
System.out.println("conn:"+conn);
//准备操作数据库
//Statement:用于执行静态SQL语句并返回它所生产结果的对象
stm=conn.createStatement();
String sql="select * from new_table";
rs =stm.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString("t1"));
System.out.println(rs.getBoolean("boo"));
}
System.out.println(rs);
conn.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
ConnectionFactory.Close(conn, stm, rs);
}