JDBC鏈接Mysql數據庫簡單實例

一、引入mysql-connector-java包java

Maven方法以下mysql

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>sql

 

簡單示例代碼:spa

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestConnectMysql {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //指定鏈接類型
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            //經過JDBC鏈接串獲取鏈接  
            connection = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=root&password=123456");
            statement = connection.createStatement();
            //準備執行語句
            resultSet = statement.executeQuery("select * from dept");
            while (resultSet.next()) {
                System.out.println(resultSet.getString("loc"));
            }
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //關閉鏈接
            try {
                if (resultSet != null) {
                    resultSet.close();
                    resultSet = null;
                }
                if (statement != null) {
                    statement.close();
                    statement = null;
                }
                if (connection != null) {
                    connection.close();
                    connection = null;
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        }
    }
}
相關文章
相關標籤/搜索