日期:2014-05-20  浏览次数:20890 次

求救:Java连接mySQL数据库的问题
以下是我的程序
import   java.sql.*;
public   class   testDBMS   {

/**
  *   @param   args
  */
public   static   void   main(String[]   args)   throws   ClassNotFoundException,
SQLException{
Class.forName( "com.mysql.jdbc.Driver ");
System.out.println( "111111111 ");
String   str=new   String( "0404210081 ");
// 链接并验证数据库
Connection   connection   =   DriverManager
.getConnection( "jdbc:mysql://localhost/gongyuguanli ", "root ", "0404210081 ");
System.out.println( "22222222222 ");
Statement   state=connection.createStatement();
ResultSet   result=state.executeQuery( "select   xingbie,name   from   xueshengmingdan "+
"where   xuehao   = ' "+str+ " ' ");
while   (result.next())
System.out.println(result.getString(1)+ "   "+result.getString(2));

}

}
运行是抛出异常如下:
111111111
22222222222
Exception   in   thread   "main "   com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:   You   have   an   error   in   your   SQL   syntax;   check   the   manual   that   corresponds   to   your   MySQL   server   version   for   the   right   syntax   to   use   near   '= '0404210081 ' '   at   line   1
at   com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at   com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at   com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at   com.mysql.jdbc.Connection.execSQL(Connection.java:3243)
at   com.mysql.jdbc.Connection.execSQL(Connection.java:3172)
at   com.mysql.jdbc.Statement.executeQuery(Statement.java:1197)
at   testDBMS.main(testDBMS.java:17)
请问是为什么啊   ????我搞了一个植物都不行。

------解决方案--------------------
where前面加个空格
------解决方案--------------------
Exception in thread "main " com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '0404210081 ' ' at line 1

异常信息说的很清楚了,是说你的SQL语句写错了,不符合SQL的语法。

你看一下你的语句:
ResultSet result=state.executeQuery( "select xingbie,name from xueshengmingdan " + "where xuehao = ' "+str+ " ' ");

SQL语句拼起来是select xingbie,name from xueshengmingdanwhere xuehao = '学号 '

是xueshengmingdan和where之间少个空格。上述语句可以改成:

ResultSet result=state.executeQuery( "select xingbie,name from xueshengmingdan where xuehao = ' "+str+ " ' ");

这样就可以了。