標籤:local 查詢 this sele 分享 res 技術 http connector
java環境是:
jdk1.8 java version "1.8.0_171"
1.安裝mysql的jar
:http://dev.mysql.com/downloads/connector/j/
我下載的時候,一直打不開,開了藍燈很快就開啟了。藍燈有時候不可以用
jar支援的版本:
下載完成後,需要eclipse加入jar包:即可把jar包放進項目裡
2.建立資料庫:
CREATE TABLE `student` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
3.編寫java代碼
package test;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class MysqlDemo { final static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; final static String DB_URL = "jdbc:mysql://localhost:3306/mv?serverTimezone=UTC"; final static String USER = "root"; final static String PASS = "root"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Connection conn = null; Statement stmt = null; Class.forName(JDBC_DRIVER); System.out.println("串連資料庫..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); // 執行查詢 stmt = conn.createStatement(); String sql = "select * from student"; ResultSet rs = stmt.executeQuery(sql); // 展開結果集 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("ID:" + id); System.out.println("name:" + name); System.out.println("age:" + age); } }}
執行結果:成功
4.遇到的問題:
4.1 The server time zone value ‘?й???????‘ is unrecognized or represents more than one time zone
解決:
jdbc:mysql://localhost:3306/mv?serverTimezone=UTC
4.2 Loading class `com.mysql.jdbc.Driver‘. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver‘. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary
解決:原來的driver有修改
final static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
java 串連資料庫