如何将MySQL与Java连接?
我已经安装了 MYSQLSERVER 5.1 .然后我安装了mysql-connector-java-3.0.8-stable-bin.jar并将其放入具有文件夹C:\ core的驱动器c中.在计算机的属性中,我创建了具有变量名CLASSPATH和变量值的用户变量:C:\ core \ mysql-connector-java-3.0.8-stable-bin.jar.
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.
现在我已经创建了数据库EMPLOYEE4 我的Java代码是:
Now I have created database EMPLOYEE4 My java code is:
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
}
}
}
我收到以下错误消息:java.sql.SQLEXCEPTION:通信链接失败:java.IO.Exception的根本原因:输入流的意外结束
I get error that java.sql.SQLEXCEPTION:communication link failure:java.IO.Exception underlying cause:Unexpected end of input stream
您应该获得NPE.在dbCon
而不是dbcon
You should be getting NPE. As you are executing your query on dbCon
and not on 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);
编辑
这就是您的代码的样子.
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);