eclipse连接MySQL数据库

首先导入JDBC包

mysql-jdbc-CSDN下载点击打开链接


Eclipse工程连接Mysql说明_百度经验 https://jingyan.baidu.com/article/fb48e8be386b7c6e622e1488.html


然后就是在eclipse中建一个项目,编写语句如下:

String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/sc";//3306是我的mysql占用端口号,sc是我提前建好的数据库
String user = "root";//mysql用户名
String password = "root";;//mysql密码

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try{//注:此次一定要加异常处理,因为diver不一定能正确找到
	//1.注册驱动
	Class.forName(driver);
	//2.获取链接
	conn = DriverManager.getConnection(url,user,password);
	//3.预处理sql
	String sql = "select * from tbl_student";
	pstmt = conn.prepareStatement(sql);
	//4.执行sql操作(更新操作,查询操作),如果有结果集处理集合
	rs = pstmt.executeQuery();
	while(rs.next()){
		long id = rs.getLong("id");
		String name = rs.getString("name");
		System.out.println(id+","+name);
	}
}catch(Exception e){
	e.printStackTrace();
}finally{
	//5.释放资源
	if(rs != null){
		rs.close();
	}
	if(pstmt != null){
		pstmt.close();
	}
	if(conn != null){
		conn.close();
	}
}

另一种sql语句,更新,删除,修改操作,无结果集合:

//4.执行sql
String sql = "insert into tbl_student(name,birth) values(?,?)";//占位符
PreparedStatement pstmt = conn.prepareStatement(sql);
//5.替换占位符
pstmt.setString(1, "terry");
pstmt.setString(2,"女");
int num = pstmt.executeUpdate();
System.out.println("保存了"+num+"条信息");
//更新操作,对所有数据有影响操作

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值