1. 程式人生 > 實用技巧 >JDBC入門

JDBC入門

JDBC代表Java資料庫連線,用於資料庫連線和執行sql語句。

第一個jdbc例項:

mysql驅動版本mysql-connector-java-8.0.16.jar
package
com.test; import java.sql.*; public class JDBC01 { public static void main(String[] args) { ResultSet rs = null; Connection connection = null; PreparedStatement statement = null;
try { //1,載入驅動 Class.forName("com.mysql.cj.jdbc.Driver"); //2.建立連線 //此處按照實際的資料庫名稱和賬號密碼進行修改 //格式為jdbc:mysql://127.0.0.1:3306/資料庫名稱?useSSL=true&characterEncoding=utf-8&user=賬號名&password=密碼 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=true&characterEncoding=utf-8&user=root&password=123456&serverTimezone=UTC"); System.out.println(
"建立連線成功"); //3.寫sql //根據資料庫實際的表名寫SQL語句 String sql="select * from pet"; //4.得到statement物件執行sql statement = connection.prepareStatement(sql); //5.得到結果集 rs = statement.executeQuery(); //6.處理結果集 while(rs.next()){ System.out.println(rs.getString(
1)); System.out.println(rs.getString(2)); System.out.println(rs.getString(3)); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { //7.關閉 if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement!=null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } System.out.println("關閉成功"); } } }

第一次接觸sql注入問題,嘗試一下學校的教務網站,好像被查水錶了。

//輸入password為123' or '1'='1
select * from users where username='123' or '1'='1' and password='123' or '1'='1’;