首页 > 代码库 > Java 连接 MySQL 数据库

Java 连接 MySQL 数据库

下载 MySQL 数据库:http://dev.mysql.com/downloads/mysql/ ,解压到本地即可

下载 jar 包:http://dev.mysql.com/downloads/connector/j/ ,下载 zip 压缩包

 

创建数据库并插入若干数据:

create table mydb;

use mydb;

create table student(name varchar(8), no char(7));

insert into student values(zhang, 011);
insert into student values(li, 021);

select * from student;

 

数据库连接类:

package g.dao;

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

public class DbConnection {
    
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/mydb";
        
        Connection connection = DriverManager.getConnection(url, "root", "root");

        return connection;
    }

    public static void free(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

测试JDBC连接:

package g.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestJDBC {

    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DbConnection.getConnection();
            String sql = "select * from student";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();

            while (resultSet.next()) {
                System.out.println(resultSet.getString("name") + " : "
                        + resultSet.getString("no"));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}