Java 连接 MySQL 数据库

时间:2014-05-13 19:36:49   收藏:0   阅读:386

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

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

 

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

bubuko.com,布布扣
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;
bubuko.com,布布扣

 

数据库连接类:

bubuko.com,布布扣
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();
        }
    }
}
bubuko.com,布布扣

 

测试JDBC连接:

bubuko.com,布布扣
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();
        }
    }
}
bubuko.com,布布扣

 

Java 连接 MySQL 数据库,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!