Query a MySQL db using java

Lexicon picture Lexicon · Apr 27, 2011 · Viewed 77k times · Source

Guys, simply put, I have a java application with a text output box. I'd like to query a Db and display the output into a text box.

Example I have a Db with two columns food and color

I'd like to :

SELECT * in Table WHERE color = 'blue'

Any suggestions?

Answer

euphoria83 picture euphoria83 · Apr 27, 2011

Beginners generally face problems understanding how to connect to MySQL from Java. This is the code snippet that can get you up and running quickly. You have to get the mysql jdbc driver jar file from somewhere (google it) and add it to the classpath.

Class.forName("com.mysql.jdbc.Driver") ;
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DBNAME", "usrname", "pswd") ;
Statement stmt = conn.createStatement() ;
String query = "select columnname from tablename ;" ;
ResultSet rs = stmt.executeQuery(query) ;