public static void main(String[] args)
{
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
/*
* 1.load the driver
* driver class :com.mysql.jdbc.Driver
*/
try {
Driver driverref=new Driver();
DriverManager.registerDriver(driverref);
/*
* 2.get db connection via driver
*/
String DbUrl="jdbc:mysql://localhost:3306/college?user=suhas&password=j2ee";
con=DriverManager.getConnection(DbUrl);
/*
* 3.issue SQL queries via Connection
*/
String query="select * from Students_info where regno=?"
+"firstname=?";
pstmt=con.prepareStatement(query);
String regnum=args[0];
int regno=Integer.parseInt(regnum);
pstmt.setInt(1,regno);
pstmt.setString(2, args[1]);
rs=pstmt.executeQuery();
/*
* 4.process the results returned by sql query
*/
while(rs.next()){
int dbregno=rs.getInt("regno");
String fname=rs.getString("firstname");
String mname=rs.getString("middlename");
String lname=rs.getString("lastname");
System.out.println("regno "+dbregno);
System.out.println("first name "+fname );
System.out.println("middlename "+mname);
System.out.println("lastname "+lname);
}//end of while
}
catch (SQLException e)
{
e.printStackTrace();
}
finally{
/*
* close all jdbc objects
*/
try {
if(con!=null){
con.close();
}
if(pstmt!=null){
pstmt.close();
}
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} 使用上面的代码我无法在运行配置中传递args值。获取数字格式异常如何解决此问题。如何在运行配置的Arguments选项卡中传递args。
答案 0 :(得分:0)
仔细查看您的代码:
String query="select * from Students_info where regno=?"
+"firstname=?";
完全等同于
String query="select * from Students_info where regno=?firstname=?";
当您用查询参数regno = 1
和args[1] = "Gord"
替换时,让我们假装。请求的SQL查询如下所示:
select * from Students_info where regno=1firstname='Gord'
这不是有效的语法。需要使用布尔运算符组合WHERE子句中的两个条件:AND
或OR
。因此,您的原始查询字符串必须是
String query="select * from Students_info where regno=?"
+" AND firstname=?";
或
String query="select * from Students_info where regno=?"
+" OR firstname=?";