import java.sql.*;
public class MySQLConn {
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/mydb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,userName,password);
Statement stmt= conn.createStatement();
System.out.println("Connected to the database ");
String query="select * from mytab";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
-----------------------------------------------------
Note : We need to add a jar to the classpath.
ie., for Oracle - ojdbc14.jar
for MySQL - "mysql-connector-java-3.1.12-bin"
In the above code : mydb is the database name
No comments:
Post a Comment