Lexicon Lexicon - 5 days ago 6
Java Question

Query a MySQL db using java

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

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) ;
Comments