Database plays an important role in storing large amount of information in a manageable manner. Connecting Java with database can make J2EE based web app really effective. All the customer information can be stored inside the database. And also its really easy to work with database like mysql.
This article will teach you on how you may connect java with database like mysql
Here we are going to learn following
First we will start with making some database in mysql along with some table
For this simply download MySql GUI editor, this will make things very easy.
Open the query Browser of Mysql and then make a new Database and make some tables inside it
Fill the table with some data
Now the most important thing while connecting Java with MySql is that you will require a library called mysql-connector-java-5.1.6-bin.jar.Here, the version may vary.You need to include this library in build path.
After this we are ready to make the java program to connect to mysql
Listing1: Connecting to mysql
import java.sql.*;
public class Java2MySql
{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "demo”
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "mypasswd";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here,
Now we will learn to select and insert values in database
Listing2: Selecting and Inserting Values
import java.sql.*;
public class Java2MySql
{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "demo";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "mypassword";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM event");
while (res.next()) {
int id = res.getInt("id");
String msg = res.getString("msg");
System.out.println(id + "\t" + msg);
}
int val = st.executeUpdate("INSERT into event VALUES("+1+","+"'Easy'"+")");
if(val==1)
System.out.print("Successfully inserted value");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here,
This is all for this article. See you next time with some more exciting articles







See the prices for this post in Mr.Bool Credits System below: