数据库访问JDBC

1,查询数据库的7个标准步骤java

1)载入JDBC驱动程序数据库

只须要在Class.forName方法中指定数据库驱动程序类名。服务器

try {
Class.forName("connect.microsoft.MicrosoftDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.sybase.jdbc.SybDriver");
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
}

2)定义URLoracle

链接URL是指服务器的主机名,端口以及但愿与之创建链接的数据库名spa

String host = "dbhost.yourcompany.com";
String dbName = "someName";
int port = 1234;
String oracleURL = "jdbc:oracle:thin:@" + host +
":" + port + ":" + dbName;
String sybaseURL = "jdbc:sybase:Tds:" + host +
":" + port + ":" + "?SERVICENAME=" + dbName;
String msAccessURL = "jdbc:odbc:" + dbName;

3)创建链接code

有了链接URL,用户名,密码,就能够创建到数据库对象

String username = "jay_debesee";
String password = "secret";
Connection connection =
DriverManager.getConnection(oracleURL, username, password);

4)建立Statement对象get

建立Statement对象才能向数据库发送查询和命令io

Statement statement = connection.createStatement();

5)执行查询或更新table

有了Statement对象后,就可使用execute,executeQuary,executeUpdate或executeBatch方法发送SQL语句到数据库

String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet = statement.executeQuery(query);

6)结果处理

数据库查询执行完毕后,返回一个ResultSet,ResultSet表示一系列的行和列,可使用next和各类getXxx方法来处理这些行和列

next/previous

getXxx

wasNull

findColumn

getRow  等方法

 

7)关闭链接

connection.close();

相关文章
相关标签/搜索