Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to start JDBC/MySQL connection DB?

Need demo and show the steps

user-image
Question added by Usama Saad , Senior Software Engineer (Java) , Saudi Catering Company
Date Posted: 2013/08/23

<p>import java.sql.*;</p> <p> </p> <p>/**</p> <p> * * *</p> <p> * </p> <p> * @author * Rayyidh</p> <p> * </p> <p> */</p> <p> </p> <p>public class Jdbcmysqlconn {</p> <p>// JDBC driver name and database URL</p> <p>static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";</p> <p>static final String DB_URL = "jdbc:mysql://localhost/spares";</p> <p> </p> <p>// Database credentials</p> <p>static final String USER = "username";</p> <p>static final String PASS = "password";</p> <p> </p> <p>public static void main(String[] args) {</p> <p>Connection conn = null;</p> <p>Statement stmt = null;</p> <p>try {</p> <p>// STEP2: Register JDBC driver</p> <p>Class.forName("com.mysql.jdbc.Driver");</p> <p> </p> <p>// STEP3: Open a connection</p> <p>System.out.println("Connecting to database...");</p> <p>conn = DriverManager.getConnection(DB_URL, USER, PASS);</p> <p> </p> <p>// STEP4: Execute a query</p> <p>System.out.println("Creating statement...");</p> <p>stmt = conn.createStatement();</p> <p>String sql;</p> <p>sql = "SELECT id, first, last, age FROM Employees";</p> <p>ResultSet rs = stmt.executeQuery(sql);</p> <p> </p> <p>// STEP5: Extract data from result set</p> <p>while (rs.next()) {</p> <p>// Retrieve by column name</p> <p>int id = rs.getInt("id");</p> <p>int age = rs.getInt("age");</p> <p>String first = rs.getString("first");</p> <p>String last = rs.getString("last");</p> <p> </p> <p>// Display values</p> <p>System.out.print("ID: " + id);</p> <p>System.out.print(", Age: " + age);</p> <p>System.out.print(", First: " + first);</p> <p>System.out.println(", Last: " + last);</p> <p>}</p> <p>// STEP6: Clean-up environment</p> <p>rs.close();</p> <p>stmt.close();</p> <p>conn.close();</p> <p>} catch (SQLException se) {</p> <p>// Handle errors for JDBC</p> <p>se.printStackTrace();</p> <p>} catch (Exception e) {</p> <p>// Handle errors for Class.forName</p> <p>e.printStackTrace();</p> <p>} finally {</p> <p>// finally block used to close resources</p> <p>try {</p> <p>if (stmt != null)</p> <p>stmt.close();</p> <p>} catch (SQLException se2) {</p> <p>}// nothing we can do</p> <p>try {</p> <p>if (conn != null)</p> <p>conn.close();</p> <p>} catch (SQLException se) {</p> <p>se.printStackTrace();</p> <p>}// end finally try</p> <p>}// end try</p> <p>System.out.println("Goodbye!");</p> <p>}// end main</p> <p>}// end Jdbcmysqlconn</p>

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.