连接java和mysql

时间:2011-10-16 16:35:17

标签: java jdbc

我使用以下代码连接java和mysql,但是 它找不到JDBC_DRIVER。我该如何解决这个问题?

以下是代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;

/*This code connects to the mysql database*/
public class mysqlconn 
{
    public Connection con = null;
    public Statement statement= null;
    public String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    public String username = "root",password = "taskinn432175";
    static String dbname = "jdbc:mysql://localhost/shopkeeper";
    String sql="select * from shopkeeper";
    String dbtime;

    public  mysqlconn(String userd , String passd){
        this.password = passd;
        this.username= userd;
    }

    public void Connect() {
        try {
            Class.forName(JDBC_DRIVER);
            con = DriverManager.getConnection(dbname,username,password);
            statement= con.createStatement();
            System.out.println ("Database connection established");
            System.out.println("capturing from database");
            ResultSet rs=statement.executeQuery(sql);
            while (rs.next()) {
                dbtime = rs.getString(1);
                System.out.println(dbtime);
            }
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null,"not connected"+e.getMessage());
        }
    }

    public static void main( String args[] )
    {
        mysqlconn conn=new mysqlconn("taskin","taskinn432175");
        conn.Connect();
    }
}

2 个答案:

答案 0 :(得分:1)

确保您的类路径中有JDBC drivers for mySql

一种方法(对于像这样的简单测试程序):

java -cp .;path_to_jdbc_connector; mysqlconn

答案 1 :(得分:0)

运行它时必须使用mysql连接器(.jar)文件以及该程序,也可以通过为应用程序创建DSN来解决此问题。