Java教程

Java SE 使用JDBC对mysql数据库的增删改查 (法一)

本文主要是介绍Java SE 使用JDBC对mysql数据库的增删改查 (法一),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 DBHelper.java

package school;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBHelper {

	public static final String url="jdbc:mysql://127.0.0.1/school?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
	public static final String name="com.mysql.cj.jdbc.Driver";
	public static final String user="root";
	public static final String  password="root";
	
	public Connection conn=null;
	public PreparedStatement pst=null;
	
	public DBHelper(String sql) throws  Exception{
		
			Class.forName(name);  //指定连接类型
			conn=DriverManager.getConnection(url,user,password);//获取连接
			pst=conn.prepareStatement(sql);//准备执行语句
			
		
	}
	
	
	public void close() throws SQLException{
		this.conn.close();
		this.pst.close();
		
	}
	
	
	
}

Insert.java

package school;

public class Insert {
static String sql=null;
static DBHelper db=null;
static int ret=0;

public static void main(String[]args) throws Exception{
	sql="insert into t_student values('11','prince','m')";//sql语句
	db=new DBHelper(sql);
	
	ret=db.pst.executeUpdate(sql);
	System.out.println("成功加入"+ret+"行");
	
}

}

 Update.java

package school;

import java.sql.ResultSet;

public class Update {
	static String sql=null;
	static DBHelper db=null;
	static int ret=0;
	
	

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
     sql="update t_student set stuname='prince2021' where stuno='1'" ;
     db=new DBHelper(sql);
     ret=db.pst.executeUpdate(sql);
     
     System.out.println("成功更新"+ret+"行");
	}

}

Select.java

package school;

import java.sql.ResultSet;

public class Select {
	static String sql=null;
	static DBHelper db=null;
	static ResultSet ret=null;
	
	public static void main(String[]args) throws Exception{
		sql="select * from t_student";//SQL语句
		db=new DBHelper(sql);
		
		ret=db.pst.executeQuery();//执行语句,得到结果集
		
		while(ret.next()){
			String id=ret.getString(1);
			String name=ret.getString(2);
			String sex=ret.getString(3);
			System.out.println(id+"\t"+name+"\t"+sex);		
		}
		ret.close();
		db.close();
		
		
	}
	
	
}

Delete.java

package school;

public class Delete {
	static String sql=null;
	static DBHelper db=null;
	static int ret=0;
	
	public static void main(String[]args) throws Exception{
		sql="delete from t_student where stusex='m'";//sql语句
		db=new DBHelper(sql);
		
		ret=db.pst.executeUpdate(sql);
		System.out.println("成功shan删除"+ret+"行");
		
	}
}

这篇关于Java SE 使用JDBC对mysql数据库的增删改查 (法一)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!