import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DoInsert {
private Connection conn=null;
private Statement stmt=null;
private String driver="com.mysql.jdbc.Driver";
private String username="root";
private String password="123456";
private String sql=
"INSER INTO student(name myclass score) VALUES('卞志成','0801','80')";
public boolean addStudent(){
boolean flag=false;
try{
//第一步 : 加载数据库厂商提供的驱动程序
Class.forName(driver);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
//第二步 : 提供数据库的连接url;
String url="jdbc.mysql://localhost:3306/test";
try{
//第三步 :通过DriverManager获得数据库的一个连接对象
conn=DriverManager.getConnection(url, username, password);
}catch(SQLException e){
e.printStackTrace();
}
try{
//第四步 :创建Statement(SQL的执行环境)
stmt=conn.createStatement();
//第五步 :执行SQL语句
int row=stmt.executeUpdate(sql);
//第六步 : 处理结果
if(row==1)
flag=true;
}catch(SQLException e)
{
e.printStackTrace();
}finally{
//第七步 : 关闭JDBC的资源
if(null!=stmt)
{
try{stmt.close();}
catch(SQLException e){e.printStackTrace();}
}
if(null!=conn){
try{conn.close();}
catch(SQLException e){
e.printStackTrace();
}
}
}
return flag;
}
public static void main(String[] args)
{
DoInsert doinser=new DoInsert();
boolean flag =doinser.addStudent();
if(flag)
{
System.out.println("添加信息成功");
}
else{
System.out.println("添加信息失败");
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.taxswyjk.dbtodb.DbToDbException;
import com.taxswyjk.dbtodb.bean.DbToDbConBean;
public class DbToDbCon {
public Connection getDBCon(String conID) throws DbToDbException {
// 返回连接
DbToDbConBean conBean = DbToDbConBean.loadFromDB(conID);
return getDBCon(conBean);
}
public Connection getDBCon(DbToDbConBean conBean) throws DbToDbException {
// 返回连接
Connection conn;
String url = conBean.getUrl();
String user = conBean.getUsername();
String password = conBean.getPassword();
String driverClass = conBean.getDrivers();
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e1) {
// TODO catch 异常处理 throw new DbToDbException("加载数据驱动失败!",e1);
}
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO catch 异常处理 throw new DbToDbException("连接失败!", e);
}
return conn;
}
}