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();
            }
        }
    }
}
相关文章
相关标签/搜索