Java连接MySQL数据库并实现增删改查

首先我们需要连接数据库,我这里选择的是MySQL数据库 我们需要做的第一件事就是加载驱动

采用下列语句加载MySQL驱动

Class.forName("com.mysql.jdbc.Driver");

驱动加载成功后就可以创建连接对象,这里会使用到java.sql.Connection Connection可以通过getConnection(url,username,password)函数获得

    url的格式为: jdbc:mysql://localhost:port/dbname port为端口号,一般默认为3306 dbname为想要连接数据库的名字,我这里是test username:数据库登录的用户名,我这里是root password:用户名对应的密码,我这里是123456
Connection conn = null;
try {
          
   
		conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", "123456");
	        System.out.println("获取数据库连接成功!");
	} catch (SQLException e) {
          
   
		System.out.println("获取数据库连接失败!");
                       //添加一个println,如果连接失败,检查连接字符串或者登录名以及密码是否错误
		e.printStackTrace();
	}

之后就是执行数据库操作,在执行操作前我们要创建一个执行SQL语句的对象state

Statement state=conn.createStatement();

在执行操作前随便建了一个数据库,这是初始数据库中information表,只有一个name一个age属性 增加操作

//向数据库插入记录
String sqlInsert = "Insert into information values(lijunjun,25)";
//受影响的行数
int rowsInsert=state.executeUpdate(sqlInsert);
System.out.println("插入行数"+rowsInsert);

控制台执行结果 此时去数据库刷新可得,标明插入成功 同理还有删除、更改、查找操作 查找操作因为返回的是结果集所以稍有不同

//删除数据库记录
String sqlDelete = "delete from information where age=25";
//受影响的行数
int rowsDelete=state.executeUpdate(sqlDelete);
System.out.println("删除行数"+rowsDelete);

//更新数据库操作
String sqlUpdate = "Update information set age=26 where name=meimei";
//受影响的行数
int rowsUpdate=state.executeUpdate(sqlUpdate);
System.out.println("更新行数"+rowsUpdate);
      
//查询数据库操作
String sqlSelec = "select age from information where name=huahu";
ResultSet rsSelect=state.executeQuery(sqlSelec);
//遍历输出结果集
while(rsSelect.next())
	{
          
   
		String age=rsSelect.getString("age");
		System.out.println(age);
	}

操作结束之后一定一定要记得关闭ResultSet对象、Statement对象和Connection对象

关闭顺序是 ResultSet对象->Statement对象->Connection对象

//关闭ResultSet对象
if(rsSelect!=null)
{
          
   
	try {
          
   
		rsSelect.close();
		System.out.println("结果集已关闭");
	} catch (SQLException e) {
          
   
		// TODO Auto-generated catch block
		e.printStackTrace();
		conn=null;
	}
}

//关闭Statement对象
if(state!=null)
{
          
   
	try {
          
   
		state.close();
		System.out.println("Statement对象已关闭");
	} catch (SQLException e) {
          
   
		// TODO Auto-generated catch block
		e.printStackTrace();
		conn=null;
	}
}
//关闭Connection对象
if(conn!=null)
{
          
   
	try {
          
   
		conn.close();
		System.out.println("数据库连接已关闭");
	} catch (SQLException e) {
          
   
		// TODO Auto-generated catch block
		e.printStackTrace();
		conn=null;
	}
}
}

这样就可以顺序的利用Java进行数据库操作了,希望能帮到你!

经验分享 程序员 微信小程序 职场和发展