public class MainApp {
static final String JDBC_DRIVER="oracle.jdbc.driver.OracleDriver";
static final String DB_URL="jdbc:oracle:thin:@localhost";
static final String USER="system";
static final String PASS="system";
public static void main (String args[])
{
Connection conn=null;
Statement stmt=null;
try{
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to Database.....");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt=conn.createStatement();
//stmt.executeUpdate("CREATE table Driver (phoneNumber number(10) primary key, licenseNumber number(5),driverName varchar(30),address varchar(10))");
//stmt.executeUpdate("INSERT into Driver values (9013105837,12347,'sunny','Delhi')");
String sql;
sql="SELECT phoneNumber,licenseNumber,driverName,address FROM Driver";
//insert a new record
Scanner sc = new Scanner(System.in);
System.out.println("Phone Number:");
long phone = sc.nextLong();
System.out.println("License Number:");
long license=sc.nextLong();
System.out.println("Name:");
String name = sc.next();
System.out.println("Address:");
String address = sc.next();
stmt.executeUpdate("INSERT into `Driver` values ("+phone+"," + license +",'" + name + "','" + address + "')");
//search by phone number(primary key)
//search by license number
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
long pn=rs.getLong("phoneNumber");
long ln=rs.getLong("licenseNumber");
String dn=rs.getString("driverName");
String add =rs.getString("address");
System.out.println("Phone Number:" +pn);
System.out.println("License Number:" +ln);
System.out.println("Name:" +dn);
System.out.println("Address:" +add);
System.out.println("--end of record--");
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Done!!");
}
}
}
我可以轻松插入静态值,但是当我尝试从用户那里获取输入时,我得到一个例外。
OUTPUT
Connecting to Database.....
Creating statement...
Phone Number:
9013020737
License Number:
12349
Name:
rohit
Address:
dwarka
java.sql.SQLException: ORA-00911: invalid character
我似乎无法弄清楚我提供的无效字符。请帮忙。我是jdbc的新手,所以如果问题看起来太基础,请原谅。
答案 0 :(得分:0)
您应该使用prepareStatement插入数据。使用现有代码,如果用户将O'Reilly输入名称输入,会发生什么?
请改为尝试:
PreparedStatement pst = conn.prepareStatement("insert into driver values (?,?,?,?)");
pst.setLong(1,phone);
pst.setLong(2,license);
pst.setString(3,name);
pst.setString(4,address);
pst.executeQuery();