Java数据库_JDBC04(例子)
主函数
package com.wang.lesson02;
import com.wang.lesson02.utils.JdbcUtils;
import java.sql.*;
import java.util.Date;
public class TestPrepareStatement {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into users (id,Name,PASSWORD,email,birthday) "+
"values(?,?,?,?,?);";
pst = conn.prepareStatement(sql);
pst.setInt(1,5);
pst.setString(2,"sb");
pst.setString(3,"123456");
pst.setString(4,"836717172@qq.com");
pst.setDate(5,new java.sql.Date(new Date().getTime()));
int i = pst.executeUpdate();
if(i>0) System.out.println("插入成功...");
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.release(conn,pst,rs);
}
}
}
辅助类JDBCUtils
package com.wang.lesson02.utils;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try{
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
public static void release(Connection con, Statement st, ResultSet rs){
if (rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
mysql连接信息
driver = com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username = root
password = root