0

How do I run a MySQL Query in Java?

I saw a few examples online, but they looked strenuous. One query required 30+ lines of code, excluding connecting to the host and such.

Is there not a short, simple, easy way to run a query/fetch results from an SQL database in Java like in PHP?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Gray Adams
  • 3,147
  • 8
  • 26
  • 37
  • http://www.exampledepot.com/egs/java.sql/GetRsData.html – Bruce Jan 01 '12 at 01:34
  • 5
    @GrayAdams - the downvotes are for *research effort*. There are quite literally hundreds of tutorials available online that show you how to use a database with Java (JDBC). If you had a specific question about a problem you were having after trying to actually do something yourself, it would be appropriate for StackOverflow. – Brian Roach Jan 01 '12 at 01:52
  • StackOverflow is a Q&A site - however it is advisable to read the FAQ first. – Bruce Jan 01 '12 at 01:59
  • 2
    Just out of curiosity, what's the 30-line example? A simple query, including connection, can be done in less than that, as evidenced by Bruce's link. Without a specific issue, it's difficult to understand what problems you're actually having. – Dave Newton Jan 01 '12 at 02:16
  • I think the question does not deserve so many negative votes. For someone coming from a language like PHP, database connections in Java may appear to be more verbose. – Rahul Jan 01 '12 at 02:24
  • @Rahul They *are* more verbose--while I didn't downvote, I suspect Brian's comment regarding effort is accurate. – Dave Newton Jan 01 '12 at 02:25
  • Here is really nice example:http://stackoverflow.com/questions/5809239/query-a-mysql-db-using-java – MrHIDEn Jul 29 '13 at 20:18

1 Answers1

3

The below example shows you to connect to database and retrieve records from the table.

Connection con = null;
  String url = "jdbc:mysql://localhost:3306/";
  String db = "jdbctutorial";
  String driver = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "root";
  try{
  Class.forName(driver).newInstance();
  con = DriverManager.getConnection(url+db, user, pass);`enter code here`
  Statement st = con.createStatement();
  ResultSet res = st.executeQuery("SELECT * FROM  employee6");
  System.out.println("Emp_code: " + "\t" + "Emp_name: ");
  while (res.next()) {
  int i = res.getInt("Emp_code");
  String s = res.getString("Emp_name");
  System.out.println(i + "\t\t" + s);
  }
  }
  catch (SQLException s){
  System.out.println("SQL code does not execute.");
  }  
  catch (Exception e){
  e.printStackTrace();
  }
finally {
con.close();
}
sethupathi.t
  • 482
  • 2
  • 6