[英]Connecting to MySQL Database from java in IDE Netbeans
So this is my thing. 所以这是我的事。 I am trying to connect do MySQL Database from java. 我正在尝试从java连接到MySQL数据库。 I have downloaded connector driver from MySQL ( Its called "mysql-connector-java-5.0.8-bin.jar" ) and I added to my libraries (Im using NetBeans). 我从MySQL下载了连接器驱动程序(它叫做“mysql-connector-java-5.0.8-bin.jar” ),我添加到我的库(我使用NetBeans)。 I tried to do simple connection like this: 我试着像这样做简单的连接:
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() );
}
}
}
But this hapened: 但这件事变得很糟糕:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
I made my research on the internet and this pretty common thing, but none of the answers helped me. 我在互联网上做了我的研究,这很常见,但没有一个答案对我有帮助。 I was able connect to database through NetBeans/services, so that URL jdbc:mysql://localhost:3306/test should be correct. 我可以通过NetBeans / services连接到数据库,因此URL jdbc:mysql:// localhost:3306 / test应该是正确的。
I am using: 我在用:
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
I am afraid this is gonna have a very trivial answer, but I am stuck here for a while now and i need to move. 我担心这会有一个非常简单的答案,但我现在被困在这里一段时间,我需要移动。 So what am I missing? 那我错过了什么?
Add: 加:
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (final ClassNotFoundException e) {
e.printStackTrace();
}
}
I thing you forget to load driver . 我忘了加载驱动程序。
Class.forName("com.mysql.jdbc.Driver");
and make sure you have mysql-connector-java-5.1.22-bin
in your class path. 并确保在类路径中有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"); 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);
}
}
My class for connection: 我的班级连接:
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>");
}
}
Don't need add ClassForName. 不需要添加ClassForName。 This is necessary in older versions of java. 这在旧版本的java中是必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.