AndroidTestor
AndroidTestor

Reputation: 65

Put variable into SQL Statement (Java/SQL)

So i have two tabels, Student and Klas_student which are described below.

Student

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

Klas

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
);

As you can see in Klas_student Student references to Studentnumber in Table Studenten. Now in java i need to take studentenummer from Studenten en put that in Klas_student.

To do that i execute a query and take all studentenummer from Studenten.

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

Then i want to take value from it and i do :

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

However in sqlStudentToKlas, it doesnt take the studentnummer(result.getString(1))string as an argument.

Anybody how i could pass the result.getString(1) as an argument/variable in Values?

Thanks in advance.

Upvotes: 0

Views: 77

Answers (2)

Hasan Fathi
Hasan Fathi

Reputation: 6086

C#:

You are Using '@' to passing parameter to your query string in ADO.net

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

And Use This Tutorial :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();

And Use This Tutorial :Named Parameters for PreparedStatement

Upvotes: 0

P_M
P_M

Reputation: 2942

Here mistake:

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

you pass string studentenummer, instead of it's value. Try:

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

or

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

Upvotes: 1

Related Questions