Java 我们可以使用扫描仪输入在 jdbc 程序中将值插入数据库吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24903430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can we use scanner input for inserting values into database in jdbc program
提问by Saravanamanikandan
I have a code like this,
我有一个这样的代码
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());
}
}
}
I know it is possible through PreparedStatement
. But can anyone help me is this possible with scanner object
我知道通过PreparedStatement
. 但是任何人都可以帮助我这是否可以使用扫描仪对象
采纳答案by Elliott Frisch
Yes, it is possible. It should look something like
对的,这是可能的。它应该看起来像
String sql = "insert into tbl1(id,catagory) values(?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, a);
ps.setString(2, b);
ps.executeUpdate();
If you must use Statement
you should probably use something like StringEscapeUtilsbecause otherwise you might be vulnerable to SQL Injection,
如果您必须使用,Statement
您可能应该使用StringEscapeUtils 之类的东西,否则您可能容易受到 SQL 注入的攻击,
String sql="insert into tbl1(id,catagory) values('" + a + "','" + b + "')";
st.executeUpdate(sql);
回答by Emanshaun
Ofcourse it is possible. First of all as you mentiond you need to use prepared statements to avoid any SQL Injections.
当然有可能。首先,正如您提到的,您需要使用准备好的语句来避免任何 SQL 注入。
Secondly you will need to do something like the following:
其次,您需要执行以下操作:
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();
}