Connect to MySQL in Java
It’s been too long, I didnt get time to post anything OpenSource.
So here I am again with one simple class Database, to connect to MySQL in Java.
You can use this class in 2 ways –
- Specifying user,pwd and database name to connect
- Specifying connection ID and class will load rest of the variables from CONFIG file
Here I will post the Database class only, class to read config file and loading properties will be posted in different post.
The Database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import java.sql.*; public class Database { Connection conn; Statement stmt; PreparedStatement pstmt; ResultSet rs; Config cfg; int affectedRows; /*Reading From CFG*/ String dbuser,dbpwd,dbname,dbserver; public Database(){ } public Database(String database, String user,String pwd) { this.affectedRows = 0; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/"+database, user , pwd); stmt = conn.createStatement(); } catch (Exception e){ e.printStackTrace(); } } public Database(String dbid) { cfg = new Config(); this.dbname = cfg.getProperty("mStrName"+dbid); this.dbuser = cfg.getProperty("mStrUser"+dbid); this.dbpwd = cfg.getProperty("mStrPwds"+dbid); this.dbserver = cfg.getProperty("mStrHost"+dbid); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/"+this.dbname, this.dbuser , this.dbpwd); stmt = conn.createStatement(); } catch (Exception e){ e.printStackTrace(); } } public ResultSet query(String qry) { try{ rs = this.stmt.executeQuery(qry); }catch(SQLException se){ System.out.println("Error : " + se.getMessage()); } return rs; } public int update(String qry) { int count = 0; try{ count = this.stmt.executeUpdate(qry); }catch(Exception se){ System.out.println("Error : " + se.getMessage()); } return count; } } |
And here is how we are going to use this class:
1 2 3 |
Database db = new Database("mydb","myuser","mypwd"); //simple query ResultSet rs = db.query("SELECT * FROM mytable"); |
Now you can traverse record rs set in a way you want…
1 2 |
//update query int affected = db.update("DELETE FROM mytable"); |
We will shortly see how we are going to use Config class and its usage.
Summary
So now yo have seen how its easy to connect to MySQL in Java. I hope you find this example useful and you can use in any of your assignment or project.