您好,歡迎來到賦能網!

java數(shù)據(jù)庫怎么導入?java數(shù)據(jù)庫如何連接?

賦能網 2023-05-09 63

java開發(fā)中,我們需要使用數(shù)據(jù)庫,數(shù)據(jù)庫的主要作用就是對數(shù)據(jù)進行統(tǒng)一管理和控制,以保證數(shù)據(jù)的安全性和完整性,那java數(shù)據(jù)庫怎么導入?下面來我們就來給大家講解一下。

首先新建名為test的數(shù)據(jù)庫,其次執(zhí)行下面Java代碼:

import java.io.File;
import java.io.IOException;

public class MySQLDatabaseimport
{
    
    public static boolean importDatabase(String hostIP, String userName, String password, String importFilePath, String sqlFileName, String databaseName)
    {
        File saveFile = new File(importFilePath);
        if (!saveFile.exists())
        { // 如果目錄不存在
            saveFile.mkdirs(); // 創(chuàng)建文件夾
        }
        if (!importFilePath.endsWith(File.separator))
        {
            importFilePath = importFilePath + File.separator;
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysql")
            .append(" -h")
            .append(hostIP);
        stringBuilder.append(" -u")
            .append(userName)
            .append(" -p")
            .append(password);
        stringBuilder.append(" ")
            .append(databaseName);
        stringBuilder.append(" <")
            .append(importFilePath)
            .append(sqlFileName);
        try
        {
            Process process = Runtime.getRuntime()
                .exec("cmd /c " + stringBuilder.toString()); //必須要有“cmd /c ”
            if (process.waitFor() == 0)
            { // 0 表示線程正常終止。
                return true;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return false;
    }
    public static void main(String[] args) throws InterruptedException
    {
        if (importDatabase("172.16.0.127", "root", "123456", "D:\\backupDatabase", "2014-10-14.sql", "GHJ"))
        {
            System.out.println("數(shù)據(jù)庫導入成功!!!");
        }
        else
        {
            System.out.println("數(shù)據(jù)庫導入失敗!!!");
        }
    }
}

java數(shù)據(jù)庫如何連接?

Java 連接 MySQL 需要驅動包,最新版下載地址為:http://dev.mysql.com/downloads/connector/j/,解壓后得到 jar 庫文件,然后在對應的項目中導入該庫文件。

本實例使用的是 Eclipse,導入 jar 包:

MySQL 8.0 以上版本的數(shù)據(jù)庫連接有所不同:

1、MySQL 8.0 以上版本驅動包版本 mysql-connector-java-8.0.16.jar。

2、com.mysql.jdbc.Driver 更換為 com.mysql.cj.jdbc.Driver。

MySQL 8.0 以上版本不需要建立 SSL 連接的,需要顯示關閉。

allowPublicKeyRetrieval=true 允許客戶端從服務器獲取公鑰。

最后還需要設置 CST。

加載驅動與連接數(shù)據(jù)庫方式如下:

Class.forName("com.mysql.cj.jdbc.Driver");
conn = 
DriverManager.getConnection("jdbc:mysql://localhost:3306/test_demo?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","password");

創(chuàng)建測試數(shù)據(jù)

接下來我們在 MySQL 中創(chuàng)建 RUNOOB 數(shù)據(jù)庫,并創(chuàng)建 websites 數(shù)據(jù)表,表結構如下:

CREATE TABLE `websites`(
    `id`
    int(11) NOT NULL AUTO_INCREMENT
    , `name`
    char(20) NOT NULL DEFAULT 
    COMMENT 站點名稱
    , `url`
    varchar(255) NOT NULL DEFAULT 
    , `alexa`
    int(11) NOT NULL DEFAULT 0
    COMMENT Alexa 排名
    , `country`
    char(10) NOT NULL DEFAULT 
    COMMENT 國家
    , PRIMARY KEY(`id`)
) ENGINE = InnoDB AUTO_INCREMENT = 10 DEFAULT CHARSET = utf8;

插入一些數(shù)據(jù):

INSERT INTO `websites`
VALUES(1, Google, https://www.google.cm/, 1, USA), (2, 淘寶, https://www.taobao.com/, 13, CN), (3, 菜鳥教程, http://www.runoob.com, 5892, ), (4, 微博, http://weibo.com/, 20, CN), (5, Facebook, https://www.facebook.com/, 3, USA);

數(shù)據(jù)表顯示如下:

連接數(shù)據(jù)庫

以下實例使用了 JDBC 連接 MySQL 數(shù)據(jù)庫,注意一些數(shù)據(jù)如用戶名,密碼需要根據(jù)你的開發(fā)環(huán)境來配置:

MySQLDemo.java 文件代碼:
package com.runoob.test;
import java.sql.*;
public class MySQLDemo
{
    // MySQL 8.0 以下版本 - JDBC 驅動名及數(shù)據(jù)庫 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
    // MySQL 8.0 以上版本 - JDBC 驅動名及數(shù)據(jù)庫 URL
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    // 數(shù)據(jù)庫的用戶名與密碼,需要根據(jù)自己的設置
    static final String USER = "root";
    static final String PASS = "123456";
    public static void main(String[] args)
    {
        Connection conn = null;
        Statement stmt = null;
        try
        {
            // 注冊 JDBC 驅動
            Class.forName(JDBC_DRIVER);
            // 打開鏈接
            System.out.println("連接數(shù)據(jù)庫...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            // 執(zhí)行查詢
            System.out.println(" 實例化Statement對象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECt id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);
            // 展開結果集數(shù)據(jù)庫
            while (rs.next())
            {
                // 通過字段檢索
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");
                // 輸出數(shù)據(jù)
                System.out.print("ID: " + id);
                System.out.print(", 站點名稱: " + name);
                System.out.print(", 站點 URL: " + url);
                System.out.print("\n");
            }
            // 完成后關閉
            rs.close();
            stmt.close();
            conn.close();
        }
        catch (SQLException se)
        {
            // 處理 JDBC 錯誤
            se.printStackTrace();
        }
        catch (Exception e)
        {
            // 處理 Class.forName 錯誤
            e.printStackTrace();
        }
        finally
        {
            // 關閉資源
            try
            {
                if (stmt != null) stmt.close();
            }
            catch (SQLException se2)
            {} // 什么都不做
            try
            {
                if (conn != null) conn.close();
            }
            catch (SQLException se)
            {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

以上實例執(zhí)行輸出結果如下:

MySQL是一個關系型數(shù)據(jù)庫管理系統(tǒng),通過對其進行連接,就能實現(xiàn)用戶通過數(shù)據(jù)庫管理系統(tǒng)訪問數(shù)據(jù)庫中的數(shù)據(jù)。最后大家如果想要了解更多初識java知識,敬請關注賦能網。


本文鏈接:

本文章“java數(shù)據(jù)庫怎么導入?java數(shù)據(jù)庫如何連接?”已幫助 63 人

免責聲明:本信息由用戶發(fā)布,本站不承擔本信息引起的任何交易及知識產權侵權的法律責任!

本文由賦能網 整理發(fā)布。了解更多培訓機構》培訓課程》學習資訊》課程優(yōu)惠》課程開班》學校地址等機構信息,可以留下您的聯(lián)系方式,讓課程老師跟你詳細解答:
咨詢熱線:4008-569-579

如果本頁不是您要找的課程,您也可以百度查找一下: