*PROGRAM TO CONNECT A DATABASE IN JAVA*
Step 1 :-
Use any SDK to write the code. Here we are using ECLIPSE JUNO.
Step 2 :-
We need to have a DATABASE to connect to our program. Here we are using MYSQL
Step 3 :-
Create a Database.
Step 4 :-
Download the required driver. In our case we are using "mysql-connector-java-5.1.17-bin.jar" file.
Jar files can e loaded in two ways :
1. paste the required file in "jre/lib/ext" folder
2. set classpath
Step 5 :-
// Program
import java.sql.*;
class ConnectionDemo
{
public static void main(String args[])
{
try
{
class.forName("com.mysql.jdbc.Driver");// to load the jdbc driver
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/customer", "root", "root"); // customer is the name of the database root is username and root is password
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select * from details"); // details is the table name
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));// getInt() and getString() reffers to the datatype table is made with
}
}
catch(Exception e)
{}
}
}
Comments
Post a Comment