Java 通过JDBC连接Mysql数据库的方法和实例【图文说明】

JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序

如果要使用数据库就要添加数据库的驱动,不同的数据库有不用的驱动,这里就不一一说明,添加jar程序驱动包的方法就不在这里解释

下面是jdbc对mysql数据库的增删查改

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





public class MysqlUtil {
	public static void main(String[] args) throws SQLException {
		Connection connection=null;
		PreparedStatement preparedStatement=null;
		ResultSet r=null;
		//连接mysql的url
		String url="jdbc:mysql://localhost:3306/mydb?user=root&password=mysql";
		try {
			//加载mysql驱动
			Class.forName("com.mysql.jdbc.Driver");
			//连接
			connection=DriverManager.getConnection(url);
			System.out.println(connection);
			//mysqljdbc添加数据
//			String sql="insert into users(userid,username,pwd) values(1,'擎天柱','123')";
//			PreparedStatement preparedStatement=connection.prepareStatement(sql);
//			int i=preparedStatement.executeUpdate();
//			if(i==1){
//				System.out.println("添加成功");
//			}else{
//				System.out.println("添加失败");
//			}
			
			//mysqljdbc查询数据
//			String sql="select * from users";
//			preparedStatement=connection.prepareStatement(sql);
//			r=preparedStatement.executeQuery();
//			while(r.next()){
//				System.out.println(r.getString("userid")+r.getString("username")+r.getString(3));
//			}
			
			//修改数据
//			String sql="update users set pwd=? where userid=?";
//			preparedStatement=connection.prepareStatement(sql);
//			preparedStatement.setString(1,"qingtianzhu");
//			preparedStatement.setInt(2, 1);
//			int i=preparedStatement.executeUpdate();
//			if(i==1){
//				System.out.println("修改成功");
//			}else{
//				System.out.println("添加失败");
//			}
			//删除数据
			String sql="delete from users where userid=?";
			preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setInt(1, 2);
			int i=preparedStatement.executeUpdate();
			if(i==1){
				System.out.println("删除成功");
			}else{
				System.out.println("删除失败");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
//			r.close();
			preparedStatement.close();
			connection.close();
			
		}
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值