我们可以使用扫描仪输入在jdbc程序中将值插入数据库

时间:2014-07-23 06:37:54

标签: java jdbc

我有这样的代码,

import java.sql.*;
import java.util.*;
public class Connectivity {

    public static void main(String[] ar){
        /*Scanner s=new Scanner(System.in);
        String a=s.nextLine();
        String b=s.nextLine();
        // Connectivity c=new Connectivity(a,b);*/

        try{
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("connecting to databse");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/example","pic","picadmin");       
            Statement st=con.createStatement();

            String sql="insert into tbl1(id,catagory) values('102','medicines')";

            st.executeUpdate(sql);
            System.out.println("Successfully Inserted");
            ResultSet rs=st.executeQuery("select * from tbl1");
            while(rs.next()){
                System.out.println(rs.getInt(1)+"  " + rs.getString(2));
            }
            con.close();
        } catch(Exception e) {
            System.out.println(e.getMessage()); 
        }
    }
}

我知道可以通过PreparedStatement。但任何人都可以通过扫描仪对象来帮助我吗

2 个答案:

答案 0 :(得分:1)

是的,有可能。它应该看起来像

String sql = "insert into tbl1(id,catagory) values(?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, a);
ps.setString(2, b);
ps.executeUpdate();

如果你必须使用Statement,你应该使用像StringEscapeUtils这样的东西,否则你可能容易受到SQL注入攻击,

String sql="insert into tbl1(id,catagory) values('" + a + "','" + b + "')";
st.executeUpdate(sql);

答案 1 :(得分:1)

当然有可能。首先,正如您所提到的,您需要使用预准备语句来避免任何SQL注入。

其次,您需要执行以下操作:

Scanner s = new Scanner(System.in);
System.out.println("Please Enter Category name:");
String catName = s.nextLine();

Connection conn = null;
PreparedStatement stmt = null;
try{
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/example","pic","picadmin"); 
    String sql="insert into tbl1(id,catagory) values('102', ?)";
    stmt = conn.prepareStatement(sql);
    stmt.setString(1, catName);
    stmt.execute()
} catch (SQLException se){
    System.out.println(se.getMessage());
} finally {
    conn.close();
}