【java 操作mysql】java連線mysql資料庫並查詢資料
阿新 • • 發佈:2019-01-25
做java開發不可避免要處理資料庫,所以這裡寫篇用jdbc來連線mysql的文章,java是一種高效能,通用的語言 。這使得它適合於編寫高效的ETL生產程式碼和計算密集型的機器學習演算法。
主要內容包括:
- 1、java連線mysql
- 2、java查詢mysql資料。
- 3、java插入mysql資料。
- 4、java更新mysql資料。
- 5、java刪除mysql資料。
- 6、java執行mysql儲存過程。
ide: IntelliJ IDEA2017
這裡必不可少的需要匯入mysql-connector-java-5.1.45-bin.jar包。
maven載入驅動
<dependency >
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
新增maven依賴好之後,編譯build,就自動載入 驅動好了。
下面是java操作mysql程式碼:
package DataStructureAndAlgorithm;
/**
* Created by Administrator on 2017/12/24.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class test6JavaJdbc {
public static void main(String[] args) {
Connection con;
String driver="com.mysql.jdbc.Driver";
//這裡我的資料庫是cgjr
String url="jdbc:mysql://localhost:3306/cgjr?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String user="root";
String password="12345";
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed()) {
System.out.println("資料庫連線成功");
}
Statement statement = con.createStatement();
// 執行查詢語句
String sql = "select * from persons;";//我的表格叫persons
ResultSet resultSet = statement.executeQuery(sql);
// 列印查詢出來的東西
String name;
String num;
while (resultSet.next()) {
name = resultSet.getString("name");
num = resultSet.getString("num");
System.out.println(name+'\t'+num);
}
// 執行插入語句
String sql2="INSERT INTO `persons` (`name`, `num`) VALUES ('徐志摩', '45');";
statement.executeUpdate(sql2);
// 執行更新語句
String sql3="UPDATE persons set num=66 WHERE `name`=\"徐志摩\"";
statement.executeUpdate(sql3);
// 執行刪除語句
String sql4="delete from persons WHERE `name`=\"徐志摩\"";
statement.executeUpdate(sql4);
// 執行呼叫儲存過程
String sql5="call add_student(3)";
statement.executeUpdate(sql5);
// 關閉連線
resultSet.close();
con.close();
System.out.println("資料庫已關閉連線");
} catch (ClassNotFoundException e) {
System.out.println("資料庫驅動沒有安裝");
} catch (SQLException e) {
System.out.println("資料庫連線失敗");
}
}
}
執行結果:
資料庫連線成功
zhangsan 20
laidefa 24
張3 57
徐志摩 66
資料庫已關閉連線
Process finished with exit code 0