我想使用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);
}
}
}
答案 0 :(得分:0)
在Class.forName
中,您必须添加驱动程序的类名
Class.forName("com.mysql.jdbc.Driver");
并且您必须在类路径中拥有mysql-connector-java-<version>-bin.jar
。
答案 1 :(得分:0)
我在你的程序中发现错误的事情
Class.forName("MySQL (Connector/J driver)");
在这里,您应该写出Class.forName("com.mysql.jdbc.Driver");
String URL = "jdbc:mysql://localhost/ mysql";
最后写的mysql
一词应该是数据库的名称。确保mysql
中有一个名为MySQL Server
的数据库。并且名称中不应有空格。
所以它应该是String URL = "jdbc:mysql://localhost:3306/databaseName";
SELECT * FROM Customers WHERE CustomerName = Alfreds Futterkiste
应该是SELECT * FROM Customers WHERE CustomerName = 'Alfreds Futterkiste'