I'm doing a program of Libros
and Autores
where a autor
has many libros
.
When inserting a new Libro
I need to get id
of autor
to save it as fk_dni
in table Libros
, so I have the following code which loads me combobox
with the Autores
that are stored 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: The set of results has no current row
So I gather that my program is not entering my while
loop.
In case I delete the single quotes in my query fk_dni
, the error that throws me is:
The value is not configured for parameter number 1.
The System.out.println("DNI : " + rs.getString(1));
is temporary since I only use it to confirm that the data is displayed correctly.