用的MYSQL的驱动链接
package com.sg.test;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Base {
public static void main(String[] args) {
try {
Base.test01();
} catch (Exception e) {
e.printStackTrace();
}
}
static void test01() throws Exception {
// 注册驱动
//第一种
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//第二种
System.setProperty("jdbc:drivers", "com.mysql.jdbc.Driver");
//第三种 (推荐使用)
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
java.sql.Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/jdbc", "root", "root");
// 创建语句
Statement st = conn.createStatement();
// 执行语句
ResultSet rs = st.executeQuery("select * from user");
// 处理结果
while (rs.next()) {
System.out.println("id:" + rs.getInt(1) + "\n name:"
+ rs.getString(2) + "\n age:" + rs.getInt(3) + "\n sex"
+ rs.getString(4) + "\n brithday:" + rs.getDate(5));
}
//关闭资源
rs.close();
st.close();
conn.close();
}
}
封装一个jdbcUtil类
package com.sg.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class jdbcUtil {
static String url = "jdbc:mysql://localhost:3306/jdbc";
static String username = "root";
static String password = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
public static void free(Statement st, Connection conn, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
}
}
单例模式 考虑并发延迟
jdbcUtil02
public final class jdbcUtil02 {
static String url = "jdbc:mysql://localhost:3306/jdbc";
static String username = "root";
static String password = "root";
// private static jdbcUtil02 instance = new jdbcUtil02();
private static jdbcUtil02 instance = null;
// 构造私有化
private jdbcUtil02() {
}
// 提供一个公共的static方法
public static jdbcUtil02 getInstance() {
// 延迟加载 使用的时候new
// 处理并发问题 可以加锁
synchronized (jdbcUtil02.class) {
if (instance == null) {
instance = new jdbcUtil02();
}
}
return instance;
}
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
}