数据库连接池
时间:2021-07-01 10:21:17
帮助过:18人阅读
java.sql.*
;
public class JDBCDemo {
public static void main(String[] args) {
//加载数据库的驱动 mysql: com.mysql.jdbc.Driver
try {
Class.forName("com.mysql.jdbc.Driver"
);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/**
* 获取数据库的连接 DriverManager
* URL格式:
* jdbc:数据库子协议(mysql/oracle/sql sever) ://ip:port/database_name
* 数据库的连接URL: jdbc:mysql://localhost:3306/exercise exercise 是库名 3306数据库端口号
*
* 用户名:root
* 密码:123456
*/
//获取数据库的连接 DriverManager
try {
/**
* getConnection源码
* * @param url a database url of the form
* * @return a connection to the URL
* 返回一个URL
* 所以必须捕获异常,防止url为空
* * @exception SQLException if a database access error occurs or the url is
* * {@code null}
* * @throws SQLTimeoutException when the driver has determined that the
* * timeout value specified by the {@code setLoginTimeout} method
* * has been exceeded and has at least tried to cancel the
* * current database connection attempt
*/
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/exercise", "root", "123456"
);
//获取Statement的实例:通过connect实例获取
/**
* createStatement
* Creates a <code>Statement</code> object for sending SQL statements to the database.
* 把sql语句给数据库
*/
Statement statement =
connection.createStatement();
/**
* 执行SQL:1.创建基本的statement对象
* Statement statement = connection.createStatement();
*/
//执行SQL
String sql = "select * from student"
;
//将SQL提交给MySQL数据库
/**
* executeQuery
* * Executes the given SQL statement, which returns a single <code>ResultSet</code> object.
* 执行sql语句
*/
ResultSet resultSet =
statement.executeQuery(sql);
//对结果集的处理
System.out.println("SID:Sname:Ssex:Sage"
);
while (resultSet.next()) {
//boolean next() 判断返回结果集中是否还有数据
//指定属性名
String sid = resultSet.getString("SID"
);
String sname = resultSet.getString("Sname"
);
String ssex = resultSet.getString("Ssex"
);
String sage = resultSet.getString("Sage"
);
System.out.println(sid+":"+sname+":"+ssex+":"+
sage);
}
//关闭资源
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据库连接池
标签:stack ase 格式 gets creates and base 连接池 ISE