Java是用JDBC连接MySQL数据库

首先要下载Connector/J地址:http://www.mysql.com/downloads/connector/j/

这是MySQL官方提供的连接方式:

解压后得到jar库文件,需要在工程中导入该库文件

我是用的是Eclipse:


 

 JAVA连接MySQL稍微繁琐,所以先写一个类用来打开或关闭数据库:

DBHelper.java

 

package com.hu.demo;

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

public class DBHelper {
    public static final String url = "jdbc:mysql://127.0.0.1/student";
    public static final String name = "com.mysql.jdbc.Driver";
    public static final String user = "root";
    public static final String password = "root";

    public Connection conn = null;
    public PreparedStatement pst = null;

    public DBHelper(String sql) {
        try {
            Class.forName(name);//指定连接类型
            conn = DriverManager.getConnection(url, user, password);//获取连接
            pst = conn.prepareStatement(sql);//准备执行语句
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            this.conn.close();
            this.pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

再写一个Demo.java来执行相关查询操作

Demo.java

 

package com.hu.demo;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Demo {

    static String sql = null;
    static DBHelper db1 = null;
    static ResultSet ret = null;

    public static void main(String[] args) {
        sql = "select *from stuinfo";//SQL语句
        db1 = new DBHelper(sql);//创建DBHelper对象

        try {
            ret = db1.pst.executeQuery();//执行语句,得到结果集
            while (ret.next()) {
                String uid = ret.getString(1);
                String ufname = ret.getString(2);
                String ulname = ret.getString(3);
                String udate = ret.getString(4);
                System.out.println(uid + "\t" + ufname + "\t" + ulname + "\t" + udate );
            }//显示数据
            ret.close();
            db1.close();//关闭连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

 

 测试数据库是在上一章 中建立的,所以直接查询

 结果和用C#连接MySQL查询的结果一样

 

 

 

posted @ 2014-04-01 20:07  zhangyongjian  阅读(240)  评论(0编辑  收藏  举报