JDBC连接数据库步骤
一、加载JDBC驱动程序
二、创建数据库连接
三、创建Statement或PreparedStatement对象
四、执行SQL语句
五、处理sql的返回结果
六、关闭创建的各个对象
package com.prenatalscreen.util.JDBCUtil;
import com.prenatalscreen.model.Dept;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
public class Jdbc {
private static Logger log = LoggerFactory.getLogger(Jdbc.class);
private static String driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=mydatabasename";
private static String user = "sa";
private static String password = "123456";
public static void main(String[] args) {
Dept dept = new Dept();
ResultSet result = null;
PreparedStatement prepareStatement = null;
Connection connection = null;
try {
connection = JDBCUtil.getConnection();
// 创建Statement或PreparedStatement对象
String sql = "SELECT * FROM dept where d_name = ? ";
String d_name = "开发部";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1,d_name);
// 执行sql语句获得结果集
result = prepareStatement.executeQuery();
// 处理结果
while(result.next()) {
dept.setD_code( result.getString("d_code"));
dept.setD_type(result.getString("d_type"));
}
} catch ( Exception e) {
log.info("数据库驱动加载失败!");
e.printStackTrace();
} finally{
releaseSourse(connection, prepareStatement, result);
}
log.info(dept.getD_code()+","+dept.getD_type());
}
/**
* 获取数据库连接的方法
* @return Connection conn
* @throws SQLException
*/
public static Connection getConnection() throws Exception {
//1.加载数据库驱动
Class.forName(driverClassName);
//2.连接数据库
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
/**
* 释放连接的方法
* @param conn 数据库连接对象
* @param stmt 执行SQL语句的对象
* @param result 执行SQL语句的返回的结果集
* @throws SQLException
*/
public static void releaseSourse(Connection conn, PreparedStatement stmt, ResultSet result) {
if (result != null) {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}