首页 > 代码库 > jdbc连接数据库
jdbc连接数据库
以mysql为例!
步骤:贾琏欲执事
1:加载数据库驱动
2:获取连接对象(DriverManager)
3:获取语句对象
4:执行语句
5:释放资源(后开的先释放)
代码:
package cn.nick.utils.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import cn.nick.domain.User;
public class JdbcUtil {
private JdbcUtil() {
}
private static Connection conn;
private static PreparedStatement ps;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///ff";
String user = "root";
String password = "nick";
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void save(User user){
String sql = "insert into user(name,password) values(‘"+user.getName()+"‘,‘"+user.getPassword()+"‘)";
try {
ps = conn.prepareStatement(sql);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
jdbc连接数据库