基本方式
连接步骤
* 1.加载JDBC驱动类
* 2.通过URL获取Connection连接
* 3.创建Statement
* 4.执行SQL语句
* 5.处理结果集
* 6.关闭连接
实现代码
public void base() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=root");
Statement stmt = con.createStatement();
String sql = "select * from user";
stmt.executeUpdate(sql);
sql = "select * from where username=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "zs");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + rs.getString(2)
+ rs.getString(3));
}
stmt.close();
stmt.close();
rs.close();
con.close();
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动类,驱动类加载失败!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
利用c3p0连接池连接数据库
所需jar包
mchange-commons-0.2.jar
c3p0-0.92-pre1.jar
mysql-connector-java-5.1.28-bin.jar
配置文件
文件位置:项目src目录下
文件名称:c3p0-config.xml
配置内容:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>
实现代码
public class JDBCUtil {
/**
* 使用默认配置文件
*/
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
/**
* 使用连接池返回一个连接
*
* @return返回Connection对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static DataSource getDataSource() {
return dataSource;
}
}