|||
根据API编写的程序都可以与驱动管理器进行通信,而驱动管理器通过遍历已注册的驱动程序找到对应的驱动程序与数据库建立通信。
注册驱动器类
如果驱动程序JAR不支持自动注册驱动程序,可以用两种注册驱动器方式。一种是在JAVA程序中加载驱动器类,例如:
Class.forName(dbInfo.getDbDivers());
另一种是设置jdbc.drivers属性,可以通过下面的方式设置系统属性。
System.setProperty("jdbc.drivers", dbInfo.getDbDivers());
连接数据库
通过DriverManager类的getConnection静态方法与数据库建立连接,返回java.sql.Connection对象。
执行SQL语句
在执行SQL语句之前,首先需要创建一个Statement对象。
Connection、Statement和ResultSet的管理
一般,每个Connection对象可以创建一个或者多个Statement对象。每个Statement对象可以用于多个不相关的命令和查询。但是,一个Statement对象最多只能打开一个结果集。
为了提高执行效率,尽量使用组合查询的方式获取一个结果集。
Connection、Statement和ResultSet使用完毕,应立即close掉。
预备语句(Prepared Statement)
当希望一个查询语句可重复使用时,可考虑准备一个带有宿主变量的查询语句。这样,每次查询时,只需给宿主变量填入不同的字符串即可。在预备语句中,宿主变量都用“?”表示,如果存在多个宿主变量,只需注意变量的位置即可。例如:
String sql = "select * from xt{0}ywbill where billid='?' and ywid='?'";
sql = MessageFormat.format(sql, new Object[] { "20000002" });
// 返回一个含预编译语句的PreparedStatement对象,sql包含一个或多个?指明的参数占位符
PreparedStatement state = connection.prepareStatement(sql);
state.setString(1, "2024");
state.setString(2, "2");
ResultSet set = state.executeQuery(sql);SQL转义
转义主要用于以下数据库支持的特性:
· 日期和时间字面常量;
· 调用标量函数;
· 调用存储过程;(需要使用call转义命令调用存储过程)
· 外连接;
· 在LIKE子句中的转义字符。代码实现:
/**
* 从database.properties配置文件中获取数据库连接信息..
* @return
*/
public static DBInfo getDBInfo() {
Properties pro = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream("database.properties");
pro.load(in);
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
DBInfo dbInfo = new DBInfo();
dbInfo.setDbDivers(pro.getProperty("jdbc.drivers"));
dbInfo.setUrl(pro.getProperty("jdbc.url"));
dbInfo.setUserName(pro.getProperty("jdbc.username"));
dbInfo.setPassWord(pro.getProperty("jdbc.password"));
return dbInfo;
}
/**
* 在驱动管理器中注册数据库驱动程序,并利用数据库信息与相应数据库建立连接..
*
* @return
*/
public static Connection getConnection() {
final DBInfo dbInfo = getDBInfo();
final String driver = dbInfo.getDbDivers();
final String url = dbInfo.getUrl();
final String user = dbInfo.getUserName();
final String password = dbInfo.getPassWord();
Connection connection = null;
try {
// 注册驱动器类
// Class.forName(driver);
if (driver != null ) {
System.setProperty("jdbc.drivers", driver);
}
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 执行SQL语句..
*
* @throws SQLException
*
*/
public static void executeQuery () throws SQLException {
Connection connection = getConnection();
try {
Statement state = connection.createStatement();
state.executeUpdate("CREATE TABLE Greetings(Message CHAR(20))");
state.executeUpdate("INSERT INTO Greetings VALUES ('Hello,ChengDong')");
ResultSet set = state.executeQuery("SELECT * FROM Greetings");
if (set.next()) {
System.out.println(set.getString(1));
}
// 关闭结果集
set.close();
state.close();
} finally {
// 关闭连接,释放当前创建的JDBC资源
connection.close();
}
}
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-6-17 06:24
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社