加載驅動java
String url="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT"; String username="root"; String password="123456"; Class.forName("com.mysql.cj.jdbc.Driver");//這裏不知道爲何加載com.mysql.jdbc.Driver會報錯,有知道的大佬請留言
鏈接數據庫,表明數據庫mysql
Connection connection = DriverManager.getConnection(url, username, password);
向數據庫發送SQL的對象Statement: CRUDsql
Statement statement = connection.createStatement();
編寫SQL (根據業務, 不一樣的SQL)數據庫
String str1="select * from users"; String str2="insert into users values (4,'趙六','145667','werwef.@eq',current_time) ,(5,'田七','53234','fsd@df',current_time)"; String str3="delete from users where id=5"; String str4="update users set password='987654' where id=4";
執行SQL安全
// int i = statement.executeUpdate(str2); // int i = statement.executeUpdate(str3); // int i = statement.executeUpdate(str4); ResultSet resultSet = statement.executeQuery(str1);
遍歷結果集url
while (resultSet.next()){ System.out.println("id:"+resultSet.getInt("id")); System.out.println("name:"+resultSet.getString("name")); System.out.println("password:"+resultSet.getString("password")); System.out.println("email:"+resultSet.getString("email")); System.out.println("birthday:"+resultSet.getString("birthday")); }
關閉鏈接3d
resultSet.close(); statement.close(); connection.close();
statement.executeQuery(); //執行查詢操做code
statement.executeUpdate(); //執行增刪改操做server
resultset. beforeFirst(); // 移動到最前面對象
resu1tSet. afterlast(); //移動到最後面
resultset.next(); //移動到下一個數據
resultset. previous(); //移動到前一行
resu1tset. absolute(row); //移動到指定行
statement不安全使用prepareStatement 能夠防SQL注入
如下是prepareStatement 的使用方法
public static void main(String[] args) throws ClassNotFoundException, SQLException { String url="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT"; String username="root"; String password="123456"; //加載驅動 Class.forName("com.mysql.cj.jdbc.Driver"); //鏈接數據庫 Connection connection = DriverManager.getConnection(url, username, password); //編寫SQL String str5="insert into users (id,name,password,email,birthday)values (?,?,?,?,?)"; //預編譯 PreparedStatement ps = connection.prepareStatement(str5); ps.setInt(1,6); //給第一個佔位符?賦值6 ps.setString(2,"胡八"); //給第二個佔位符?賦值"胡八" ps.setString(3,"1223235"); //給第三個佔位符?賦值」1223235「 ps.setString(4,"ew@12"); //給第四個佔位符?賦值"ew@12" ps.setDate(5,new Date(new java.util.Date().getTime())); //給第五個佔位符?賦值2020-05-19 //執行 int i = ps.executeUpdate(); if (i>0){ System.out.println("插入成功"); } //關閉鏈接 ps.close(); connection.close(); }