Java数据库MySQL演讲_Java 连接MySql数据库

看此文请注意几点:1. 数据库的结构在 最后运行结果中. 数据库名: work01_school; 表名: students;

2.这是写给我自己看, 看不懂没关系,这是有我之前学习数据库的地址链接结合书上的知识点.

代码1: 用于连接到数据库的测试:

Connection con=null;

try{ //第一步: 加载驱动:

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

System.out.println("1.加载驱动成功!");

}catch(Exception e){

System.out.println("1.加载驱动异常!");

e.printStackTrace();

}

try{ //第二步: 使用驱动管理程序连接数据库:

con=DriverManager.getConnection("jdbc:mysql://localhost:3306","root","root");

System.out.println("2.连接数据库成功!");

Statement stmt=con.createStatement();

stmt.close();

con.close();

}catch(SQLException e){

System.out.println("2.连接数据库异常!");

e.printStackTrace();

}

代码2: 对数据库 进行一些简单 查询、更新、删除 操作:

package SqlJava;

import java.sql.*;

public class $_3_UpdataDelete {

public static void main(String[] args) {

try{

//1.加载驱动

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

System.out.println("1.成功加载MySql驱动!");

//2.连接到数据库

String url="jdbc:mysql://localhost:3306/work01_school";

Connection conn;

conn = DriverManager.getConnection(url,"root","root");

Statement stmt = conn.createStatement(); //使用Statement对象的executeQuery("SQLcode")操作sql语句.

System.out.println("2.成功连接到数据库!");

//3.查询数据表中的数据

String sql="select * from students";

ResultSet rs= stmt.executeQuery(sql); //执行语句查询.

System.out.println("编号\t姓名\t年龄");

while(rs.next()){

System.out.print(rs.getInt(1)+"\t");//当前行第一个位置

System.out.print(rs.getString(2)+"\t");//当前行第2个位置

System.out.print(rs.getInt(3)+"\t");//当前行第3个位置

System.out.println(); //给当前行 换行

}

//4.修改数据表中的的数据:

String sql2 = "update students set name=? where classId=?";

PreparedStatement pst= conn.prepareStatement(sql2);

pst.setString(1,"中国");

pst.setInt(2,2);

pst.executeUpdate();

//5.删除数据表中的数据:

String sql3="delete from students where classId=?";

// ? 号是提供未知的参数,从1开始。

pst=conn.prepareStatement(sql3);

pst.setInt(1,3);

pst.executeUpdate();

ResultSet rs2 = stmt.executeQuery(sql);

System.out.println("编号\t姓名\t年龄");

while(rs2.next()){

System.out.print(rs2.getInt(1)+"\t");

System.out.print(rs2.getString(2)+"\t");

System.out.print(rs2.getInt(3)+"\t");

System.out.println();

}

rs.close();

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

}

}

运行结果:

39459c3c4522842038be9be6b57ee60f.png

The End;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值