package jsbc;
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) {
Connection c = null;
Statement s = null;
try {
//初始化驱动
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("数据可加载成功!!!");
//建立数据库连接
c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306" +
"/how2java?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC","root","123");
System.out.println("连接成功,获取对象:"+c);
//创建Statement语句
s = c.createStatement();
//增加
//String sql = "insert into hero values (null,"+"'提莫'"+","+313.0f+","+50+")";
/*for(int i=0;i<5;i++){
String sqlStr = "insert into hero values(null,"+"'hero"+i+"'"+","+313.0f+","+50+")";
s.execute(sqlStr);
}*/
//删除
//String sql = "delete from hero where id=5";
//修改
//String sql = "update hero set name = 'new name' where id = 3";
//s.execute(sql);
//查询
String sql = "select * from hero";
ResultSet rs = s.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString(2);
float hp = rs.getFloat("hp");
int damage = rs.getInt(4);
System.out.printf("%d\t%s\t%f\t%d%n",id,name,hp,damage);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
if(s!=null){
try {
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(c!=null){
try {
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
java基础——jdbc基本操作
最新推荐文章于 2022-11-25 15:33:25 发布