任何程序的实战应用都是与数据库有关,因为在用户操作过程中肯定有互动,有互动意味着有数据的读取,更新等操作,接下来由百恒科技工程师向大介绍java连接mysql实现数据增加、删除、修改、查询的基本操作.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
//写一个通用类,操作数据库,即我们通常执行sql语句
public class OperateDB{
public static ResultSet queryDB(Statement sm,String sql){
ResultSet rs= null;
try{
rs=sm.executeQuery(sql);
} catch (SQLException e){e.printStackTrace();}
return rs;
}
public static int updateDB(Connection con ,String sql){
Statement sm=null;
int affectRows=0;
try {sm=con.createStatement();
affectRows=sm.executeUpdate(sql);
}catch(SQLException e){
e.printStackTrace();
affectRows=Statement.EXECUTE_FAILED;}
finally {closeStatement(sm);}
return affectRows;
}
public static void showResultSet(ResultSet rs){
if (rs==null){return;}
try{ResultSetMetaData md=rs.getMetaData();
int columnCount=md.getColumnCount();
if (!rs.isBeforeFirst()){rs.beforeFirst();}
while(rs.next()){
for (int i=1;i System.out.print(rs.getObject(i)+"t");
}
System.out.print(rs.getObject(columnCount)+"rn");
}
rs.beforeFirst();
}catch(SQLException e){e.printStackTrace();}
}
public static void closeStatement(Statement sm){
if(sm!=null){
try{
sm.close();
}catch (SQLException el){el.printStackTrace();}
}
}
public static void closeConnection(Connection con){
if(con !=null){
try{
con.close();
}catch (SQLException el){el.printStackTrace();}
}
}
public static void main(String[] args)throws ClassNotFoundException,SQLException{
String dbName="test";
String userName="root";
String password="123456";
String querySQL="SELECT *FROM student";
String updateSQL="UPDATE student SET EnglishObj=100 where UserName='百恒科技'";
String insertSQL="INSERT INTO student(UserName,UserSex,ChineseObj) values('刘工','男','88')";
//String deleteSQL="Delete from student where UserName='刘工'";
Connection con=null;
Statement sm=null;
try{
con=DBConnector.getMySQLConnection(null,null,null,dbName,userName,password);
sm=con.createStatement();
ResultSet rs=OperateDB.queryDB(sm, querySQL);
System.out.println("修改数据表之前的数据");
OperateDB.showResultSet(rs);
OperateDB.updateDB(con,updateSQL);
OperateDB.updateDB(con, insertSQL);
//OperateDB.updateDB(con, deleteSQL);
System.out.println();
System.out.println("修改数据表之后的数据");
rs=OperateDB.queryDB(sm, querySQL);
OperateDB.showResultSet(rs);
System.out.println();
rs.absolute(1);
System.out.print("UserName:" +rs.getString("UserName")+"t");
System.out.println("EnblishObj"+rs.getInt("EnglishObj"));
rs.absolute(3);
System.out.print("UserName:" +rs.getString("UserName")+"t");
System.out.println("EnblishObj"+rs.getInt("EnglishObj"));
rs.close();
}catch (ClassNotFoundException el){
throw el;
}catch (SQLException e2){
throw e2;
}finally{
closeStatement(sm);
closeConnection(con);
}
}
}
原创文章出自:百恒网络 如转载请注明出处!专业,专注于南昌网站建设,为用户提供高品质的网络产品及优质服务是我们始终的追求.