我刚才编写了这么一段代码
package jdbc;
import java.sql.*;
public class TestPreStmt {
public static void main(String[] args) {
String sname = args[0];
String sno = args[1];
String ssex = args[2];
String sage = args[3];
Connection conn = null;
PreparedStatement pstmt = null;
if(args.length != 4){
System.out.println( "parameter Error! Please input again! ");
System.exit(-1);
}//如果参数个数不是3,错误退出.
/*
try{
sname=Integer.parseInt(args[0]);
}catch(NumberFormatException e){
System.out.println( "parameter format Error! ");
System.exit(-1);
} //将传过来的参数转换成int型
*/
try{
Class.forName( "com.mysql.jdbc.Driver ");
//mysql数据库的驱动
//Class.forName( "oracle.jdbc.driver.OracleDriver ");
//oracle数据库的驱动
conn = DriverManager.getConnection( "jdbc:mysql://localhost/dd ", "root ", "2244982 ");
//连接数据库.
String sql = "insert into t(sname,sno,ssex,sage) values(?,?,?,?); ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, sname);
pstmt.setString(2, sno);
pstmt.setString(3, ssex);
pstmt.setString(4, sage);
System.out.println(sql);//将sql语句打印出来,便于调试
pstmt.executeUpdate(sql);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(pstmt !=null){
pstmt.close();
pstmt =null;
}
if(conn !=null){
conn.close();
conn =null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
最后报出这段错误
insert into t(sname,sno,ssex,sage) values(?,?,?,?);
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 '?,?,?,?) ' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3118)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1313)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1232)
at jdbc.TestPreStmt.main(TestPreStmt.java:42)
不知是何原因,请高手指导!
------解决方案--------------------
String sql = "insert into t(sname,sno,ssex,sage) values(?,?,?,?) ";
不用加分号
------解决方案--------------------
楼上给你指出来了