JDBC的简单连接

对于传统的jdbc连接可以把它分为4个步骤:(当前以mysql数据库为例)

1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");//mysql的连接
//Class.forName("oracle.jdbc.driver.OralceDriver"); Oralce的连接
2.建立连接
conn = DriverManager.getConnection(url, username, password);
3.执行sql
private static void select(Connection conn, long id) throws SQLException {
String sql = "SELECT id, username FROM es_user WHERE id = ?";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
String userName = rs.getString(2);
System.out.println("id=" + id + "userName=" + userName);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
ps.close();
}
}
4.关闭流
conn.close();
 rs.close();
ps.close();

完整代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;

public class JDBCTest {
static String url = "相应的地址";
static String username = "username";
static String password = "password";

public static void main(String[] args) {
connection();
}

private static void connection() {
Connection conn = null;
try {
// 1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");//mysql的连接
//Class.forName("oracle.jdbc.driver.OralceDriver"); Oralce的连接
//2.建立连接
conn = DriverManager.getConnection(url, username, password);
//3.执行sql
select(conn, 1131117546905276417L);
//4.关闭流
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void select(Connection conn, long id) throws SQLException {
String sql = "SELECT id, username FROM es_user WHERE id = ?";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
String userName = rs.getString(2);
System.out.println("id=" + id + "userName=" + userName);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
ps.close();
}
}
}


posted @ 2020-02-28 15:52  享受饥饿  阅读(110)  评论(0)    收藏  举报