JDBC连接mysql

环境搭建

1.确认mysql的运行状态

打开cmd,输入命令mysql。

如果没有安装mysql安装图解 mysql图文安装教程(详细说明)

2.下载并安装驱动

下载地址http://dev.mysql.com/downloads/connector/j/

clip_image001

如果选择的是Microsoft Windows,则会下载mysql-connector-java-gpl-5.1.36.msi,安装以后在如下目录中能找到有关连接的jar包:

C:\Program Files (x86)\MySQL\MySQL Connector J //x86为可选,以自己下载版本为准

如果选择的是platform independent(与平台无关),则会下载mysql-connector-java-5.1.36.tar.gz,解压即可。

3.导入jar包

项目->Build Path->Configure Build Path

在Libraries选项卡中Add External JARs把

mysql-connector-java-5.1.36-bin.jar包导入。

测试链接

导入支持类

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

import com.mysql.jdbc.PreparedStatement;

主函数

  public static void main(String[] args) throws SQLException {
        Connection conn=getConn("root", "", "");  //没有密码就什么都不写,空字符串             
        Statement stmt=conn.createStatement();
        ResultSet rs=stmt.executeQuery("show databases");//执行查询
        while(rs.next()){//遍历查询结果
            System.out.println(rs.getString(1));
        }
stmt.close();//显示关闭Statement对象,释放资源
conn.close();
//关闭数据库连接,这是个好习惯。尽管在程序运行结束会自动关闭。但web应用是不会结束运行的。 }

连接函数

    public static Connection getConn(String username,String password,String DBname){
        String driver="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/"+DBname;
        Connection conn=null;
        try {
            Class.forName(driver);
            conn=DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException e) {            
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
posted @ 2015-08-08 20:33  klguang  阅读(6063)  评论(0编辑  收藏  举报