by
226 9
3
5
2,766
0
Top 1% !
Popular
Famous
Specified
OpenSource
Popularity: 5995th place
Created
Modified Feb 4, 2014

Published on:

No tags for this snippet yet.
ClassNameDconnector
JVMjre7
LanguageJava
LicenseMIT_X11
MethodNamegetData
OutputTypevoid

Connecting to MySQL database using JAVA

Works only after you add java mysql driver jar into your library
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/26222/Connecting-to-MySQL-database-using-JAVA?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Dconnector { private Connection con; private Statement st; private ResultSet rs; public Dconnector() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/goosehunters", "root", ""); // Connection execution takes place here st = con.createStatement(); // Statement execution takes place here } catch (Exception ex) { System.out.println("Dconnector exception => " + ex); } } public void getData() { try { String query = "SELECT * FROM goose"; rs = st.executeQuery(query); //ResultSet execution takes place here System.out.println("records from database\t"); //goose is the column name of the table goosehunters while (rs.next()) { String name = rs.getString("name"); String age = rs.getString("age"); System.out.println(name + " \t" + age); } } catch (Exception ex) { System.out.println("getData exception => " + ex); } } } //----------------------------------------MAIN CLASS-------------------------------------------// public class Main extends Dconnector { public static void main(String[] args) { Dconnector a = new Dconnector(); a.getData(); } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus