Eclipse串連MySQL資料庫,eclipsemysql資料庫

來源:互聯網
上載者:User

Eclipse串連MySQL資料庫,eclipsemysql資料庫

工作目錄:


右鍵項目,選中Build Path,選中configure build path,把lib目錄下的jar包加入路徑。

程式碼:
package com.test;import java.sql.*;//引入包public class MysqlConnTest {      public MysqlConnTest() {            status = -1;           setConnection( null);            try {                Class. forName( "com.mysql.jdbc.Driver"); //載入驅動                setConnection(DriverManager. getConnection( "jdbc:mysql://localhost:3306/test", "root", "123456")); //建立串連           } catch (Exception e) {                 e.printStackTrace();           }            status = 1;     }           public static void main(String args[]) throws SQLException{           MysqlConnTest instance = new MysqlConnTest();            if ( instance.getStatus() == 1) {                 //狀態準備好了                 instance.TestWrite();                 instance.TestRead();                                 instance.getConnection().close();           }     }           //測試寫程式      public void TestWrite() throws SQLException{           PreparedStatement statement = getConnection().prepareStatement("insert into test(name) values ('hello')");            statement.executeUpdate();     }           //測試讀程式      public void TestRead() throws SQLException{           PreparedStatement statement = getConnection().prepareStatement("select * from test" );           ResultSet result = statement.executeQuery();            while( result.next()){                System. out.println( "id = " + result.getInt(1) +",name = " + result .getString(2));           }            result.close();     }           private int status;      private Connection connection;           public int getStatus(){            return status;     }           public void setStatus( int status){            this. status = status;     }      public Connection getConnection() {            return connection;     }      public void setConnection(Connection connection) {            this. connection = connection;     }}
SQL檔案:
CREATE DATABASE  IF NOT EXISTS `test`;USE `test`;DROP TABLE IF EXISTS `test`;CREATE TABLE `test` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` varchar(45) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
運行結果:

THE END

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.