java提供了什么功能,可以从命令行中获取SQL的executeUpdate()方法的输入!

时间:2022-04-16 20:46:48
Scanner input = new Scanner(System.in);
System.out.println("Enter Staff Name: ");
String staffName = input.nextLine();
System.out.println("Enter Department Name: ");
String department =Input.nextLine();

stmt.executeUpdate("insert into staff (StaffName,department) " + "values " +  
staffName,department);

This gives me an error and asks me to check the SQL manual.Is it even possible?

这给了我一个错误,让我检查SQL手册。它甚至有可能吗?

2 个解决方案

#1


2  

It is possible, since it happened. Strings must be enclosed in quotes in SQL:

这是可能的,因为它发生了。字符串必须包含在SQL语句中:

insert into foo (bar, baz) values ('hello', 'world');

Learn to use prepared statements instead of string concatenations, to make your queries work, and not be subject to SQL injection attacks:

学习使用准备好的语句而不是字符串连接,以使查询工作,而不受SQL注入攻击的影响:

PreparedStatement stmt = connection.prepareStatement("insert into staff (StaffName, department) values (?, ?)");
stmt.setString(1, staffName);
stmt.setString(2, department);
stmt.executeUpdate();

Using the above, you don't need to mess with quotes nor escape them inside the strings.

使用上面的内容,您无需对引号进行混乱,也不需要在字符串中转义。

#2


0  

It's not necessarily the user input being formatted incorrectly. The INSERT into should be formatted like:

并不一定是用户输入的格式不正确。插入的格式应该是:

INSERT INTO <table_name>
VALUES (<1>, <2>, ... <n>);

To format your SQL query correctly, you could try:

要正确格式化SQL查询,您可以尝试:

String sql = "INSTERT INTO STAFF (StaffName, department) VALUES (\'" + 
  staffName + "\', \'" + department + "\');";

#1


2  

It is possible, since it happened. Strings must be enclosed in quotes in SQL:

这是可能的,因为它发生了。字符串必须包含在SQL语句中:

insert into foo (bar, baz) values ('hello', 'world');

Learn to use prepared statements instead of string concatenations, to make your queries work, and not be subject to SQL injection attacks:

学习使用准备好的语句而不是字符串连接,以使查询工作,而不受SQL注入攻击的影响:

PreparedStatement stmt = connection.prepareStatement("insert into staff (StaffName, department) values (?, ?)");
stmt.setString(1, staffName);
stmt.setString(2, department);
stmt.executeUpdate();

Using the above, you don't need to mess with quotes nor escape them inside the strings.

使用上面的内容,您无需对引号进行混乱,也不需要在字符串中转义。

#2


0  

It's not necessarily the user input being formatted incorrectly. The INSERT into should be formatted like:

并不一定是用户输入的格式不正确。插入的格式应该是:

INSERT INTO <table_name>
VALUES (<1>, <2>, ... <n>);

To format your SQL query correctly, you could try:

要正确格式化SQL查询,您可以尝试:

String sql = "INSTERT INTO STAFF (StaffName, department) VALUES (\'" + 
  staffName + "\', \'" + department + "\');";