簡體   English   中英

在IDE Netbeans中從java連接到MySQL數據庫

[英]Connecting to MySQL Database from java in IDE Netbeans

所以這是我的事。 我正在嘗試從java連接到MySQL數據庫。 我從MySQL下載了連接器驅動程序(它叫做“mysql-connector-java-5.0.8-bin.jar” ),我添加到我的庫(我使用NetBeans)。 我試着像這樣做簡單的連接:

package datacon;

public class Datacon {

    public static void main(String[] args) {

        try {

            java.sql.Connection con = (java.sql.Connection) java.sql.DriverManager
                .getConnection("jdbc:mysql://localhost:3306/test"
                /*, "root"
                  , "root" */ );

        } catch ( Exception e ) {
            System.out.println( e.toString() );
        }
    }
}

但這件事變得很糟糕:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test

我在互聯網上做了我的研究,這很常見,但沒有一個答案對我有幫助。 我可以通過NetBeans / services連接到數據庫,因此URL jdbc:mysql:// localhost:3306 / test應該是正確的。

我在用:

java:   Oracle java SDK 1.7.0 _ 45
IDE:    NetBeans 7.4
OS:     Debian 3.2.51-1 x86_64
Driver: MySQL Connector/J 5.0.8

我擔心這會有一個非常簡單的答案,但我現在被困在這里一段時間,我需要移動。 那我錯過了什么?

加:

static {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (final ClassNotFoundException e) {
        e.printStackTrace();
    }
}

我忘了加載驅動程序。

Class.forName("com.mysql.jdbc.Driver");

並確保在類路徑中有mysql-connector-java-5.1.22-bin

try {
      Class.forName("org.gjt.mm.mysql.Driver");
      Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    } catch(ClassNotFoundException e) {
        e.printStackTrace();
    }

try {class.forname(“com.mysql.jdbc.Driver”);

     driver.getconnection("connenctionurl","name","password");

            Statement s =goodrecive.asif().createStatement();
            s.executeUpdate("INSERT INTO product(productno,productname,quantity,ammount)values('"+t1.getText()+"','"+t2.getText()+"','"+t3.getText()+"','"+t4.getText()+"')");

    } catch (Exception e) {
        System.out.println(e);
    }
}                         

我的班級連接:

package connection;

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

public class ConnectionFactory {  
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/<database>", "<user>", "<password>");
    }        
}   

不需要添加ClassForName。 這在舊版本的java中是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM