This post
is to help initiate a MySQL database connection through Java at front-end via
JDBC (Java Data Base Connectivity).
Before this we need to know some basic information which are as follows:
Before this we need to know some basic information which are as follows:
1.
Driver class: The driver class for the MySQL
database is 'com.mysql.jdbc.Driver'.
2.
Connection URL: The connection URL for the MySQL
database is 'jdbc:mysql://localhost:3306/DB_sample' where jdbc
is the API, MySQL is the database, localhost is the server name on which MySQL
is running, we may also use IP address, 3306 is the port number and DB_sample is
the database name. We may use any database, in such case, you need to replace
the DB_sample with your database name.
3.
Username: The default username for the
MySQL database is root.
4.
Password: Password is given by the user at
the time of installing the MySQL database. In this example, we are going to use pswd as
the password.
You must initially have a database created in the name DB_sample, which
can be created in a similar fashion as rendered below,
create
database DB_sample;
use
DB_sample;
create
table employee(empid int(10), emp_name varchar(40), salary int(3));
Now
for the Java code to connect to this MySQL database is rendered below, (in this
example code as mentioned earlier DB_sample as database name, root as username
and pswd as password):
import java.sql.*;
class ClsSqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DB_sample","root","pswd");
//here DB_sample is database
name, root is username and pswd is password
Statement stmt =
con.createStatement();
ResultSet
rs=stmt.executeQuery("select * from employee");
//Fetching records of employee
record
while(rs.next())
System.out.println(rs.getInt(1)+"
"+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){
System.out.println(e);}
}
}
Using
the above code you can retrieve all records of the employee table. Hope this
helpful and you were successful in your trial to connect to the MySQL database.
Post a Comment