在Netbeans上使用JDBC链接java程序和MySQL

时间:2015-04-02 04:36:15

标签: mysql netbeans jdbc

我想使用JDBC驱动程序将Netbeans上的Java程序与MySQL链接起来。我知道有Netbeans工具可以促进连接,但我可以使用Netbeans编写的Java程序吗?

我在这里获得了教程http://www.tutorialspoint.com/jdbc/jdbc-db-connections.htm

package jdbc.connections;
import java.sql.*;  // for standard JDBC programs
import java.util.logging.Level;
import java.util.logging.Logger;

public class JDBCConnections 
{    
    public static void main(String[] args) 
    {       
        try 
        {
            //registering jdbc driver
            Class.forName("MySQL (Connector/J driver)");              
        }        
        catch(ClassNotFoundException ex) 
        {
            System.out.println("Error: unable to load driver class!");
            System.exit(1);
        }

        String URL = "jdbc:mysql://localhost/ mysql";
        String USER = "username";
        String PASS = "password";
        Connection conn;

        try             
        {
            conn = DriverManager.getConnection(URL, USER, PASS);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM Customers WHERE CustomerName = Alfreds Futterkiste");
            System.out.println(rs);
        } 
        catch (SQLException ex) 
        {
            Logger.getLogger(JDBCConnections.class.getName()).log(Level.SEVERE, null, ex);
        }           
    }    
}

2 个答案:

答案 0 :(得分:0)

Class.forName中,您必须添加驱动程序的类名

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

并且您必须在类路径中拥有mysql-connector-java-<version>-bin.jar

答案 1 :(得分:0)

我在你的程序中发现错误的事情

  1. Class.forName("MySQL (Connector/J driver)");在这里,您应该写出Class.forName("com.mysql.jdbc.Driver");

  2. 类的名称
  3. String URL = "jdbc:mysql://localhost/ mysql";最后写的mysql一词应该是数据库的名称。确保mysql中有一个名为MySQL Server的数据库。并且名称中不应有空格。

  4. 所以它应该是String URL = "jdbc:mysql://localhost:3306/databaseName";

    1. SELECT * FROM Customers WHERE CustomerName = Alfreds Futterkiste应该是SELECT * FROM Customers WHERE CustomerName = 'Alfreds Futterkiste'