Create a connection to MySQL in Java
This time we are going to create a basic connection to MySQL in Java and pull some data from it.
// Compile it:
// javac Mysql.java
//
// Try it:
// java -classpath mysql-connector-java-5.1.27-bin.jar:. MySQL
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class MySQL {
public Connection getConnection() throws SQLException {
Connection conn = null;
Properties p = new Properties();
p.put("user", "username");
p.put("password", "superpassword");
String cs = "jdbc:mysql://localhost/demo";
conn = DriverManager.getConnection(cs, p);
return conn;
}
public static void main(String[] args) {
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
MySQL mysql = new MySQL();
conn = mysql.getConnection();
stmt = conn.createStatement();
String sql = "select * from songs limit 10";
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
Happy coding…