1.工具类
package com.jdbc.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcMySqlUtil {
/**
* @param args
*/
static{
//1.注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
//2.得到连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=7654321");
return conn;
}
}
2.增删改查
package com.jdbc.demo;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
public class JdbcMySqlCRUD {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet result = null;
//1.增加信息
public void add(int id ,String name,Date birthday) {
String sql = "insert into student values(?,?,?)";
try {
conn = JdbcMySqlUtil.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.setDate(3, birthday);
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//2.删除信息
public void delete(int id) {
String sql = "delete from student where id = ?";
try {
conn = JdbcMySqlUtil.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//3.更新信息
public void update(int id ,String name) {
String sql = "update student set name=? where id = ?";
try {
conn = JdbcMySqlUtil.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.setInt(2, id);
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//4.查找信息
public void select() {
try {
conn = JdbcMySqlUtil.getConnection();
String sql = "select * from student";
pstmt = conn.prepareStatement(sql);
result = pstmt.executeQuery();
while(result.next()){
System.err.println(result.getInt("id"));
System.err.println(result.getString("name"));
System.err.println(result.getDate("birthday"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}