Step1:develop a mysql.properties file
# To change this template, choose Tools |
Templates
# and open the template in the editor.
# key=value
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bhargavi
user=root
pwd=root
Step2:develop a DBUtil.java class
It was loading a .properties file
using Properties class load() method.
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class DBUtil {
public static Connection get(){
Connection con=null;
try{
Properties p=new Properties();
p.load(DBUtil.class.getClassLoader().getResourceAsStream("mysql.properties"));
String a=p.getProperty("driver");
String b=p.getProperty("url");
String c=p.getProperty("user");
String d=p.getProperty("pwd");
Class.forName(a);
con=DriverManager.getConnection(b,c,d);
}catch(Exception e){
}
return con;
}
}
Step3:develop a DAO.java class
It is get the connection from
DBUtil class and stored into a database using prepared statement.
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import util.DBUtil;
public class DAO {
public static int insert() throws
SQLException{
int i=0;
Connection con=DBUtil.get();
PreparedStatement
stmt=con.prepareStatement("insert into employeregister values(4,'as',111,'java')");
i=stmt.executeUpdate();
return i;
}
}
Step4:develop a Insert.java class
Just create a dao class object and
call that method..
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import util.DBUtil;
public class Insert {
public
static void main(String asss[]) throws SQLException{
int i=dao.DAO.insert();
System.out.println("inserted record..");
}
}
output:
0 comments:
Post a Comment