Connecting to some sql servers with jdbc.
Download the JDBC driver for your databases and add them to the project in eclipse (or whatever) then:
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConnect{
public static void main(String args[]){
String dbtime="";String db_connect_string="";String db_userid="";String db_password="";String query="";
try {
//Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
int choose=2;
switch (choose)
{
case 0:
db_connect_string="jdbc:mysql://yourMySQLServerNameHere/yourMySQLData";
db_userid="ooooohyourusername";
db_password="waaaaaayYourPassword";
query = "Select top 10 * FROM YourTable";
break;
case 1:
db_connect_string="jdbc:sqlserver://yourSQLServerNameHere;databaseName=yourDatabaseName";
db_userid="ooooohyourusername";
db_password="waaaaaayYourPassword";
query = "Select top 10 * FROM YourTable";
break;
}
Connection con = DriverManager.getConnection(db_connect_string,db_userid, db_password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
int rn=0;
while (rs.next()) {
dbtime = rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+" "+rs.getString(5);
System.out.println(rn+" : "+dbtime);
rn++;
} con.close();
} //end try
catch(ClassNotFoundException e) {e.printStackTrace();}
catch(SQLException e) {e.printStackTrace();}
}
}