码迷,mamicode.com
首页 > 数据库 > 详细

Java 连接 MySQL 数据库

时间:2014-05-13 19:36:49      阅读:386      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

下载 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

Java 连接 MySQL 数据库

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/geb515/p/3724304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!