Created
April 12, 2020 07:58
-
-
Save saswata-dutta/12153d02027b6185dfabeb9bcc58c2cf to your computer and use it in GitHub Desktop.
sample jdbc connect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.labex; | |
import java.sql.*; | |
public class JdbcTest { | |
// JDBC driver name | |
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; | |
//database url | |
static final String DB_URL = "jdbc:mysql://localhost/example"; | |
// database user name | |
static final String USER = "root"; | |
// database user password | |
static final String PASS = ""; | |
public static void main(String[] args) { | |
Connection conn = null; | |
Statement stmt = null; | |
try{ | |
// load driver class | |
Class.forName("com.mysql.jdbc.Driver"); | |
// connect to database | |
System.out.println("Connecting to database..."); | |
conn = DriverManager.getConnection(DB_URL,USER,PASS); | |
// execute query | |
System.out.println("Creating statement..."); | |
stmt = conn.createStatement(); | |
String sql; | |
sql = "SELECT id, name, age FROM students"; | |
ResultSet rs = stmt.executeQuery(sql); | |
// get result set | |
while(rs.next()){ | |
// retrive data | |
int id = rs.getInt("id"); | |
int age = rs.getInt("age"); | |
String name = rs.getString("name"); | |
// print result | |
System.out.print("ID: " + id); | |
System.out.print(", Age: " + age); | |
System.out.print(", Name: " + name); | |
System.out.println(); | |
} | |
// release resource | |
rs.close(); | |
stmt.close(); | |
conn.close(); | |
}catch(SQLException se){ | |
// JDBC exception handle | |
se.printStackTrace(); | |
}catch(Exception e){ | |
// Class.forName error | |
e.printStackTrace(); | |
}finally{ | |
// close resource | |
try{ | |
if(stmt!=null) | |
stmt.close(); | |
}catch(SQLException se2){ | |
} | |
try{ | |
if(conn!=null) | |
conn.close(); | |
}catch(SQLException se){ | |
se.printStackTrace(); | |
} | |
} | |
System.out.println("Goodbye!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment