Created
April 23, 2023 21:35
-
-
Save pradeepnnv/6d12fe39abed13445a26ccacd4a3b36c to your computer and use it in GitHub Desktop.
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
import java.sql.*; | |
/** | |
* A Java MySQL SELECT statement example. | |
* Demonstrates the use of a SQL SELECT statement against a | |
* MySQL database, called from a Java program. | |
* | |
* Created by Alvin Alexander, http://alvinalexander.com | |
*/ | |
public class JavaMysqlSelectExample | |
{ | |
public static void main(String[] args) | |
{ | |
try | |
{ | |
// create our mysql database connection | |
//String myDriver = "com.mysql.jdbc.Driver"; | |
String myDriver = "com.mysql.cj.jdbc.Driver"; | |
String myUrl = "jdbc:mysql://DBHOSTNAME/DBNAME"; | |
Class.forName(myDriver); | |
Connection conn = DriverManager.getConnection(myUrl, "USERNAME", "PASSWORD"); | |
// our SQL SELECT query. | |
// if you only need a few columns, specify them by name instead of using "*" | |
String query = "SELECT * FROM albums"; | |
// create the java statement | |
Statement st = conn.createStatement(); | |
// execute the query, and get a java resultset | |
ResultSet rs = st.executeQuery(query); | |
// iterate through the java resultset | |
while (rs.next()) | |
{ | |
int id = rs.getInt("id"); | |
String title = rs.getString("Title"); | |
String artist = rs.getString("Artist"); | |
Date year = rs.getDate("Year"); | |
// print the results | |
System.out.format("%s, %s, %s, %s\n", id, title, artist, year); | |
} | |
st.close(); | |
} | |
catch (Exception e) | |
{ | |
System.err.println("Got an exception! "); | |
System.err.println(e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment