插入数据
import com.pan.lesson01.lesson02.utils.JdbcUtils;
import java.sql.*;
import java.util.Date;
public class TestInsert {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "INSERT INTO users(`id`,`NAME`,`PASSWORD`,`email`,`birthday`)" +
"VALUES(?,?,?,?,?)"; //使用问号占位符,代替参数
pstm = conn.prepareStatement(sql); //预编译sql,先写sql不执行
//手动给参数(?问号)赋值
pstm.setInt(1,5);
pstm.setString(2,"李洋");
pstm.setString(3,"54446666");
pstm.setString(4,"245884732@qq.com");
//注意点:sql.Date util.Date 类型包不一样 最后要把时间戳转换为java.sql.Date类型
pstm.setDate(5,new java.sql.Date(new Date().getTime()));
//执行sql
int i = pstm.executeUpdate();
if (i>0){
System.out.println("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.release((com.mysql.jdbc.Connection) conn,pstm,rs);
}
}
}
删除数据
import com.pan.lesson01.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class TestDelet {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "delete from users where id=?";
pstm = conn.prepareStatement(sql); //预编译sql,先写sql不执行
//手动给参数(?问号)赋值
pstm.setInt(1,5);
//执行sql
int i = pstm.executeUpdate();
if (i>0){
System.out.println("删除成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.release((com.mysql.jdbc.Connection) conn,pstm,rs);
}
}
}
查询数据
import com.pan.lesson01.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestSelect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "select * from users where id=?"; //编写sql
pstm = conn.prepareStatement(sql); //预编译
pstm.setInt(1,1); //传递参数 表中id=1 的第一条数据
//执行
rs = pstm.executeQuery();
if (rs.next()){
System.out.println(rs.getString("NAME"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.release((com.mysql.jdbc.Connection) conn,pstm,rs);
}
}
}
修改数据