JDBC建立連線的三種不同方式
阿新 • • 發佈:2018-12-30
public class Jdbc {
static final String JDBC_Driver = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/jdbcdemo?useSSL=false"; //MySQL在高版本需要指明是否進行SSL連線
static final String user = "root";
static final String password = "root";
public static void main(String[] args){
Connection conn = null;
Statement st = null;
try {
//第二步:註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//第三步:建立sql語句
String sql = "select id,username,age,sex,phone from sys_user";
//第四步:建立連線
conn = DriverManager.getConnection(DB_URL, user, password); //url,username,password三個引數
//第五步:執行查詢
st = conn.createStatement(); //無參
ResultSet rs = st.executeQuery(sql);
//第六步:處理結果集
while (rs.next()) {
//通過列名獲取值
int id = rs.getInt("id");
String username = rs.getString("username");
int age = rs.getInt("age");
String phone = rs.getString("phone");
//列印
System.out.print("ID: " + id);
System.out.print(", 年齡: " + age);
System.out.print(", 姓名: " + username);
System.out.println(", 電話: " + phone);
}
rs.close();
}catch (SQLException se){
se.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
//第七步 釋放資源
try {
if(st != null){
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
static final String JDBC_Driver = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/jdbcdemo?useSSL=false"; //MySQL在高版本需要指明是否進行SSL連線
static final String user = "root";
static final String password = "root";
public static void main(String[] args){
Connection conn = null;
Statement st = null;
try {
//第二步:註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//第三步:建立sql語句
String sql = "select id,username,age,sex,phone from sys_user";
//第四步:建立連線
conn = DriverManager.getConnection(DB_URL, user, password); //url,username,password三個引數
//第五步:執行查詢
st = conn.createStatement(); //無參
ResultSet rs = st.executeQuery(sql);
//第六步:處理結果集
while (rs.next()) {
//通過列名獲取值
int id = rs.getInt("id");
String username = rs.getString("username");
int age = rs.getInt("age");
String phone = rs.getString("phone");
//列印
System.out.print("ID: " + id);
System.out.print(", 年齡: " + age);
System.out.print(", 姓名: " + username);
System.out.println(", 電話: " + phone);
}
rs.close();
}catch (SQLException se){
se.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
//第七步 釋放資源
try {
if(st != null){
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}