一、JDBC的介紹
它是JAVA數據庫連接的一種連接數據庫的API。對不同的數據庫採用統一的API進行編程。
二、接口:
DriverManager:驅動程序管理類,用來管理驅動
Connection:連接指定的數據庫
Statement:執行sql語句,獲取結果
PreparedStatement:執行預編譯的sql語句
ResultSet:對結果集進行處理的方法
三、使用MySql數據庫
1.在MySql的官網上下載mysql對應的jdbc驅動
編寫JDBC的步驟:
加載驅動—打開連接—執行查詢—-處理結果—清理環境。
2.加載驅動:首先將下載的mysql-jdbc lib拷入到項目中。
3.打開連接 執行語句 處理結果 清理環境
public class LoginDao {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
/* public boolean login(String username, String password) {
boolean flag = true;
String sql = "select * from login where username=?" + username
+ "and password=?" + password;
return flag;
}*/
public boolean test() {
boolean flag = true;
String sql = "SELECT * FROM login";
try {
Class.forName("com.mysql.jdbc.Driver");// 反射Driver類上
connection = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "123456");
statement = (Statement) connection.createStatement();
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("username"));
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
if (resultSet != null)
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (statement != null)
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (statement != null) {
connection.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return flag;
}
public static void main(String[] args) {
System.out.println(new LoginDao().test());
}
}