hi all,
how to connect ur java application to sql server database.
thanks Etele
hi all,
how to connect ur java application to sql server database.
thanks Etele
Hi Etele,
Firstly, you will need a JDBC driver for your database which will also need to be put into your classpath.
Here is a snippet code which should get you started.
=======
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class JDBCTest {
public static void main (String args[]) {
JDBCTest db = new JDBCTest();
}
public JDBCTest() {
Connection connection = null;
Statement stmnt = null;
ResultSet rs = null;
try {
// Load the JDBC connector driver
Class.forName(“oracle.jdbc.driver.OracleDriver”);
String url = “jdbc:oracle:thin:@neptune:1521:EJDB”;
String usr = “username”;
String pwd = “pwd”;
connection = DriverManager.getConnection(url,usr,pwd);
stmnt = connection.createStatement();
String qry = “SELECT * FROM STUDENT”;
rs = stmnt.executeQuery(qry);
while ( rs.next() ) {
String firstColumn = rs.getString(1);
// do your own stuff here
System.out.println(firstColumn);
}
}
catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {}
}
if(stmnt != null) {
try {
stmnt.close();
} catch (SQLException e) {}
}
if(connection!= null) {
try {
connection.close();
//connection.close() throws an SQLException, but we can't recover at this point
}
catch (SQLException sqlEx) {}
}
}
}
}
=====
This is a basic example only and there are many other examples online.
Hope this helps.
Martyn