I am doing a program of Libros
and Autores
where one autor
has many libros
.
When inserting a new one, Libro
I need to obtain the id
del autor
to save it as fk_dni
in the table Libros
, so I have the following code which loads me combobox
with those Autores
that are saved in my database.
public void insertarLibro()
{
String url = "jdbc:sqlserver://localhost:1433;databaseName=Biblioteca";
String user = "mi_usuario";
String password = "mi_contraseña";
String fk_dni = "SELECT dni FROM Autores WHERE nombre = '?'";
try
{
Connection cn = DriverManager.getConnection(url, user, password);
PreparedStatement ps = cn.prepareStatement(fk_dni);
ResultSet rs = ps.executeQuery();
String nombre = (String)cboAutor.getSelectedItem();
while(rs.next())
{
ps.setString(1, nombre);
}
System.out.println("DNI : " + rs.getString(1));
}
catch(SQLException e)
{
System.out.println("ERROR : ");
e.printStackTrace(System.out);
}
}
But my program returns the following error
com.microsoft.sqlserver.jdbc.SQLServerException: Result set has no current row
So I deduce that my program is not entering my loop while
. In case I remove the single quotes in my query fk_dni
, the error it throws me is:
The value is not set for parameter number 1.
The System.out.println("DNI : " + rs.getString(1));
is temporary since I only use it to verify that the data is displayed correctly.
As @A.Cedano already said, the query does not have single quotes around the question mark:
Also, you have to pass the value to the query and then execute it
There are some errors in the code:
Misspelled prepared query. The parameter(s) to be passed in the prepared statement, indicated by
?
should not be surrounded by single quotes like you have now. Should be:You cannot do the
executeQuery
before setting the parameternombre
:Note: Searching for a DNI only by name can give you wrong data, it may be that José from Egypt is not the same as José from Nazareth.