jdbc测试类代码mysql_java JDBC测试(示例代码)

这是一个Java程序,展示了如何使用JDBC连接到MySQL数据库进行CRUD操作。代码加载了MySQL的JDBC驱动,建立了数据库连接,并执行了查询、插入、删除和更新的SQL语句。
摘要由CSDN通过智能技术生成

package com.jdbc.test;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import com.mysql.jdbc.Connection;public classJdbcTest1 {public staticConnection getConnection(){

Connection conn= null;try{

Class.forName("com.mysql.jdbc.Driver");  //加载驱动

conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false","root","123456");  //连接数据库

}catch (ClassNotFoundException |SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}returnconn;

}public static void select(){

Connection conn=getConnection();

String sql= "select *from book1";try{

Statement st=conn.createStatement();

ResultSet rs=st.executeQuery(sql);  //执行SQL语句while(rs.next()){

System.out.print(rs.getString("use_name")+" ");

System.out.println(rs.getInt("use_age")+" ");

}

rs.close();

st.close();

conn.close();

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}public static voidinsert(){

Connection conn=getConnection();

String sql= "insert into book1 values(‘lixiaoming‘,25)";try{

Statement st=conn.createStatement();int count =st.executeUpdate(sql);

System.out.println("已经向表中插入"+count+"条数据");

st.close();

conn.close();

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}public static voiddelete(){

Connection conn=getConnection();

String sql= "delete from book1 where use_age = 25";try{

Statement st=conn.createStatement();int count =st.executeUpdate(sql);

System.out.println("从表中删除了"+count+"条数据");

st.close();

conn.close();

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}public static voidupdate(){

Connection conn=getConnection();

String sql= "update book1 set use_age=30 where use_name = ‘zhangsan‘";try{

Statement st=conn.createStatement();int count =st.executeUpdate(sql);

System.out.println("从表中更新了"+count+"条数据");

st.close();

conn.close();

}catch(SQLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}public static voidmain(String[] args) {//TODO Auto-generated method stub

select();//insert();//delete();//update();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值