Skip to main content

help java to connect to db

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
2 replies [Last post]
aida91
Offline
Joined: 2011-04-03

hello evryone ihave a question:
if i want to take a query for the database for example i have this code:

public class Displayauthers {

static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static final String DATABASE_URL = "jdbc:sqlserver//localhost:1433;" +
"databaseName=DB_Library; user=sa; password=softPRO3";

/**
* @param args the command line arguments
*/
@SuppressWarnings("CallToThreadDumpStack")
public static void main(String[] args) {
// TODO code application logic here
Connection connection = null;
Statement state = null;

try
{
Class.forName( JDBC_DRIVER );

connection = DriverManager.getConnection(DATABASE_URL, "sa", "******");

state = connection.createStatement();
ResultSet rSet = state.executeQuery("select * from dbo.categories");
ResultSetMetaData metadata = rSet.getMetaData();
int numberOfColumns = metadata.getColumnCount();
System.out.println("Authers Table of library DB: ");

for(int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-8s\t%", metadata.getColumnName(i));
System.out.println();

while ( rSet.next() )
{
for( int i = 1; i <= numberOfColumns; i++ )
System.out.printf("%-8s\t", rSet.getObject(i));
System.out.println();
}
}

catch( SQLException sqlex )
{
sqlex.printStackTrace();
System.exit( 1 );
}

catch(ClassNotFoundException classNotFound )
{
classNotFound.printStackTrace();
System.exit( 1 );
}
finally
{
try
{
state.close();
connection.close();
}
catch( Exception exception )
{
exception.printStackTrace();
System.exit( 1 );
}
}
}

when i run the code it must give me the fields inside the authers table acording to this query
ResultSet rSet = state.executeQuery("select * from dbo.auther");

but it wont return any value, nor errors too!

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
slash13
Offline
Joined: 2011-06-04

Hey

The result of the query you executed is on the ResultSet object, to return a specific value you should put for example rSet.getString("name_of_column") or rSet.getString(index_of_column). The methods of ResultSet allows you to return specific types of data for example rSet.getInt for an integer

javinpaul
Offline
Joined: 2011-01-10

at little advance level you may want to wrap your code into a DATA Access Object (DAO) class or may look forward to use tools and frameworks like hibernate for interaction with Java and Database.