java 串連資料庫

來源:互聯網
上載者:User

標籤: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 串連資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.