将变量放入SQL语句(Java / SQL)

时间:2015-06-13 15:03:50

标签: java sql

所以我有两个表格,Student和Klas_student,如下所述。

学生

CREATE TABLE IF NOT EXISTS Studenten(
Studentenummer varchar(7) CHECK (Studentenummer ~'[0-9A-ZA-Z]{7}'),
}

克拉斯

CREATE TABLE IF NOT EXISTS Klas(
Student varchar(7) REFERENCES studenten (Studentenummer) ON DELETE CASCADE NOT NULL,
Klas text NOT NULL REFERENCES Klas (Naam_id) ON DELETE CASCADE NOT NULL
);

正如您在Klas_student中所见,学生对Table Studenten中的Studentnumber的引用。现在在java中我需要从Studenten采取studentenummer并将其放入Klas_student。

要做到这一点,我执行一个查询并从Studenten采取所有studentenummer。

sql = "INSERT INTO Studenten " + "VALUES ('1559335')";
statement2.executeUpdate(sql);

然后我想从中获取价值并且我这样做:

String studentnummer = result.getString(1).toString();
sqlStudenToKlas = "INSERT INTO Klas " + "VALUES (studentnummer)";
statement2.executeUpdate(sqlStudenToKlas);
conn.commit();

但是在sqlStudentToKlas中,它不会将studentnummer(result.getString(1))字符串作为参数。

任何人如何将result.getString(1)作为参数/变量传递给值?

提前致谢。

2 个答案:

答案 0 :(得分:1)

这里有错误:

sqlStudenToKlas = "INSERT INTO Klas " + "VALUES (studentenummer)";

你传递字符串studentenummer而不是它的值。尝试:

sqlStudenToKlas = "INSERT INTO Klas " + "VALUES (" + studentenummer+")";

sqlStudenToKlas = "INSERT INTO Klas " + "VALUES ('" + studentenummer+"')";

答案 1 :(得分:0)

C#:

您正在使用'@'将参数传递到ADO.net中的查询字符串

String studentnummer = result.getString(1).toString();
sqlStudenToKlas = "INSERT INTO Klas " + "VALUES (@studentenummer)";
Command.Parameters.AddWithValue("@List", studentenummer);
statement2.executeUpdate(sqlStudenToKlas);
conn.commit();

并使用本教程:The C# Station ADO.NET Tutorial

Java with JDBC:

String studentnummer = result.getString(1).toString();
sqlStudenToKlas = "INSERT INTO Klas " + "VALUES (?)";
sqlStudenToKlas.setString(1, studentenummer);
statement2.executeUpdate(sqlStudenToKlas);
conn.commit();

并使用本教程:Named Parameters for PreparedStatement