[英]How to connect MySQL with Java?
I have installed MYSQLSERVER 5.1 .Then I installed mysql-connector-java-3.0.8-stable-bin.jar and put in drive c with folder core that is C:\\core.Then in properties of computer I create user variable with variable name CLASSPATH and variable value:C:\\core\\mysql-connector-java-3.0.8-stable-bin.jar. 我已经安装了MYSQLSERVER 5.1 。然后我安装了mysql-connector-java-3.0.8-stable-bin.jar并将驱动器c放入文件夹核心即C:\\ core.Then在计算机的属性中我用变量创建用户变量名称CLASSPATH和变量值:C:\\ core \\ mysql-connector-java-3.0.8-stable-bin.jar。
Now I have created database EMPLOYEE4 My java code is: 现在我已经创建了数据库EMPLOYEE4我的java代码是:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
class MySQLTest{
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
Connection dbCon = null;
Statement stmt = null;
ResultSet rs = null;
//getting PreparedStatment to execute query
stmt = dbCon.prepareStatement(query);
//Resultset returned by query
rs = stmt.executeQuery(query);
while(rs.next()){
int count = rs.getInt(1);
System.out.println("count of stock : " + count);
}
} catch (Exception ex) {
ex.printStackTrace();
//Logger.getLogger(CollectionTest.class.getName()).log(Level.SEVERE, null, ex);
} finally{
//close connection ,stmt and resultset here
}
}
}
I get error that java.sql.SQLEXCEPTION:communication link failure:java.IO.Exception underlying cause:Unexpected end of input stream 我得到java.sql.SQLEXCEPTION的错误:通信链接失败:java.IO.Exception底层原因:意外的输入流结束
You should be getting NPE. 你应该得到NPE。 As you are executing your query on
dbCon
and not on dbcon
当您在
dbCon
上执行查询而不在dbcon
上执行查询时
// initialize here
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query ="select count(*) from EMPLOYEE4 ";
// Null here
Connection dbCon = null;
// on dbCon which is null
stmt = dbCon.prepareStatement(query);
EDIT 编辑
This how your code suppose to look like. 这就是你的代码看起来像的样子。
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EMPLOYEE", "root", "root");
String query = "select count(*) from EMPLOYEE4 ";
Statement stmt = dbcon.createStatement();
ResultSet rs = stmt.executeQuery(query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.