public class BaseDao { /** * 数据库连接字符串 */ private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/myschool?useUniCode=true&characterEncoding=utf-8"; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; private Connection conn; private PreparedStatement statement; private ResultSet rs; /** * 获取连接的方法 */ public Connection getConnection() { try { Class.forName(DRIVER); //判断连接对象是否为空或者当前连接对象是否是isClosed()已经关闭的 if(conn==null||conn.isClosed()){ conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } /** * 增删改 * * @throws Exception */ public int executeUpdate(String sql, Object... obj) throws Exception { // 获取连接 getConnection(); // 获取PreparedStatement对象 statement = conn.prepareStatement(sql); // 循环加载参数 for (int i = 1; i <= obj.length; i++) { statement.setObject(i, obj[i-1]); } // 执行SQL int count = statement.executeUpdate(); return count; } /** * 查询 * @throws SQLException */ public ResultSet executeQuery(String sql, Object... obj) throws Exception { // 获取连接 getConnection(); // 获取PreparedStatement对象 statement = conn.prepareStatement(sql); // 循环加载参数 for (int i = 1; i <= obj.length; i++) { statement.setObject(i, obj[i-1]); } rs = statement.executeQuery(); return rs; } /** * 关闭连接 * @throws Exception */ public void closeResource() throws Exception { if(rs!=null){ rs.close(); } if(statement!=null){ statement.close(); } if(conn!=null){ //关闭连接 conn.close(); } } }
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class zeng {
public static void main(String[] args) {
String ur1="jdbc:mysql:///myschool";
String username="root";
String password="";
String driver= "com.mysql.jdbc.Driver";
try {
//作用:将制定的类型的全名称包名+类名对应的类文件(class文件)装载到内存
Class . forName(driver);
} catch (ClassNotFoundException e1) {
e1. printStackTrace();
}
Connection con=null;
Statement stat=null;
//01.驱动Driver管理类Manager
try {
//接口
//02. getConnection Connection
con= DriverManager. getConnection(ur1, username, password);
//03. Statement命令对象
//连接对象----------->生命命令对象
//Alt+上下键
stat= con. createStatement() ;
//04.准备sg1
String sql="insert into dd( sname , shobby , salay) values( '123', ' coding', 10000)";
int count = stat.executeUpdate(sql);
if (count>0) {
System.out.println("add success!");
}else{
System.out.println("failed");
}
} catch (Exception e) {
e. printStackTrace();
}finally{
try {
stat. close( );
con.close();
} catch (Exception e){
e. printStackTrace();
}
}
}
}