Created
June 1, 2021 12:21
-
-
Save BT-ICD/eb7f3951d25dfc35d01f99e9d28de4a8 to your computer and use it in GitHub Desktop.
Example: To access data from MySQL database.
This file contains 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
/** | |
* Example: To access data from MySQL database. | |
* References: | |
* https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-statements.html | |
* */ | |
import java.sql.*; | |
public class JdbcDemo1 { | |
public static void main(String[] args) { | |
Connection conn = null; | |
Statement stmt =null; | |
ResultSet rs = null; | |
try { | |
// Class.forName("com.mysql.jdbc.Driver"); | |
String jdbcURL ="jdbc:mysql://localhost:3306/testdb"; | |
String userName = "root"; | |
String password = "root"; | |
conn = DriverManager.getConnection(jdbcURL,userName,password); | |
System.out.println("Connection is closed: " + conn.isClosed()); | |
stmt = conn.createStatement(); | |
rs = stmt.executeQuery("Select * From Dept"); | |
rs = stmt.getResultSet(); | |
while(rs.next()){ | |
int deptNo = rs.getInt(1); | |
String dname = rs.getString("DName"); | |
String loc = rs.getString(3); | |
System.out.println(deptNo + " - " + dname + " - " + loc); | |
} | |
rs.close(); | |
conn.close(); | |
System.out.println("Connection is closed: " + conn.isClosed()); | |
} catch (SQLException ex) { | |
System.out.println(ex.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment