Skip to content

Instantly share code, notes, and snippets.

@tuxcuiabano
Created September 24, 2019 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxcuiabano/34ea2fa374e520e270c302b2e35251e5 to your computer and use it in GitHub Desktop.
Save tuxcuiabano/34ea2fa374e520e270c302b2e35251e5 to your computer and use it in GitHub Desktop.
Exemplo do DisplayAuthors com PreparedStatement
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package deitel28;
/**
*
* @author tuxcuiabano
*/
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class DisplayAuthorsPrepared
{
// database URL
//modelo derby
// static final String DATABASE_URL = "jdbc:derby://localhost:1527/livros";
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/books";
// launch the application
public static void main( String args[] )
{
Connection connection = null; // manages connection
PreparedStatement ps = null; // query statement
ResultSet resultSet = null; // manages results
try
{
connection = DriverManager.getConnection(
DATABASE_URL, "root", "senha" );
ps = connection.prepareStatement("SELECT * FROM Authors WHERE firstName=?");
String sql = JOptionPane.showInputDialog("Digite o nome do autor");
ps.setString(1, sql);
resultSet = ps.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println( "Tabela de Autores do Banco de dados Books:\n" );
while ( resultSet.next() )
{
for ( int i = 1; i <= numberOfColumns; i++ )
System.out.printf( "%-8s\t", resultSet.getObject( i ) );
System.out.println();
} // end while
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
finally // ensure resultSet, statement and connection are closed
{
try
{
resultSet.close();
ps.close();
connection.close();
} // end try
catch ( Exception exception )
{
exception.printStackTrace();
} // end catch
} // end finally
} // end main
} // end class DisplayAuthors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment