1.导入JDBC驱动jar
2.注册JDBC驱动
参数:“驱动程序类名”
class.forname(“驱动程序类名”)
3.获得Connection对象
需要链接3个参数:url,username,password
-连接到数据库
4.创建Statement对象
-conn.getStatement()方法创建对象
用于执行sql语句
-execute(sql)执行任何sql,常用执行DDL
-executeUpdate(dml)执行dml语句 如insert,update,delete
-executeQuery(dql)如select
5.处理sql执行结果
-execute(ddl),没有异常则成功
-execute(dml),还会数字,表示更新行数量,抛出异常则失败
-execute(dql),返回ResultSet结果集对象,代表二维查询结果
使用for循环遍历失败则抛出异常
6.关闭数据库连接
conn.close()
最简单的数据库工具类:
public class DbUtil {
private static String url;
private static String user;
private static String password;
private static String driver;
public static Connection conn = null;
static {
try {
// String driver = "com.mysql.jdbc.Driver";
// url = "jdbc:mysql://127.0.0.1:3306/???";
// user = "root";
// password = "root";
// Class.forName(driver);
Properties prop = new Properties();
prop.load(new FileReader("config.properties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
try {
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw e;
}
}
}