JDBC and MySQL
I have to always connect to the database for some reason. My usual problem is “Access denied”. I thought I would document it once. The steps to start connecting to MySQL from a program are as:
1) Install MySQL server and download mysql-connector-java-3.0.17-ga.
2) Set the class path. ( could be C:\mysql-connector-java-3.0.17-ga )
3) Grant permission on the SQL server as:
GRANT ALL PRIVILEGES ON some_database.* TO ’someuser’@'localhost’ IDENTIFIED BY ’some_password’ WITH GRANT OPTION;
4) Load driver in JDBC as com.mysql.jdbc.Driver
5) Get the connection as jdbc:mysql://localhost:3306/<db_name>?user=some_user&password=some_password’6
6) Do you queries.
7) Close your connection.
You are all set.
Here is a quick example of this.
import java.io.*;
import java.sql.*;
public class SQLExample{
public static void main(String args[])
{
Connection conn = null;
Statement stmt = null;
try{
//LOAD THE DRIVER
Class.forName("com.mysql.jdbc.Driver");
//GET THE CONNECTION STRING
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db_name?
user=someuser&password=somepassword");
//GET A STATEMENT TO EXECUTE
stmt=conn.createStatement ();
String query="insert into newtable values('someName',10)";
ResultSet result = stmt.executeQuery(query);
System.out.println("query executed");
int row = result.getRow();
if(row>0)
System.out.println("Row " +row+" Added");
}catch(Exception e){
e.printStackTrace();
}
finally
{
try {
conn.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Good Luck connecting the database !
About this entry
You’re currently reading “JDBC and MySQL,” an entry on Technical Musings
- Published:
- May 7, 2008 / 6:03 pm
- Category:
- Uncategorized
- Tags:
No comments yet
Jump to comment form | comment rss [?] | trackback uri [?]