java连接数据库,执行增删改查操作


public class ConnectionDataBaseTest {

public static final String driver="com.mysql.jdbc.Driver";//驱动
public static final String url="jdbc:mysql://localhost:3306/ssm";//指向数据库名
public static final String user="root";//用户
public static final String password="root";//密码

public static void main(String[]args){
try {
Class.forName(driver);//加载驱动
Connection connection=DriverManager.getConnection(url,user,password);//创建连接
queryDataBase(connection);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
}
}

//查询数据
public static void queryDataBase(Connection connection){
try {
String sql="SELECT * FROM user";
Statement statement=connection.createStatement();
ResultSet resultSet=statement.executeQuery(sql);

int id;
String name=null;
int age;
String gender=null;
while (resultSet.next()){
id=resultSet.getInt("id");
name=resultSet.getString("name");
age=resultSet.getInt("age");
gender=resultSet.getString("gender");
System.out.println("id:"+id+";name:"+name+";age:"+age+";gender:"+gender);
}
statement.close();
resultSet.close();
} catch (SQLException e){
e.printStackTrace();
}finally {
System.out.println("数据查询成功!");
}
}

//插入数据
public static void insertDataBase(Connection connection){
try {
PreparedStatement preparedStatement=
connection.prepareStatement("INSERT INTO user(id,name,age,gender) VALUES (?,?,?,?)");
preparedStatement.setInt(1,4);
preparedStatement.setString(2,"马云");
preparedStatement.setInt(3,30);
preparedStatement.setString(4,"男");
preparedStatement.executeUpdate();//插入,修改和删除数据时都要用excuteUpdate()
preparedStatement.close();
} catch (SQLException e){
e.printStackTrace();
}
}

//修改数据
public static void updateDataBase(Connection connection){
try {
PreparedStatement preparedStatement=connection.prepareStatement("UPDATE user SET name=? WHERE id=?");
preparedStatement.setString(1,"马化腾");
preparedStatement.setInt(2,3);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

//删除数据
public static void deleteDataBase(Connection connection){
try {
PreparedStatement preparedStatement=connection.prepareStatement("DELETE FROM user WHERE id=?");
preparedStatement.setInt(1,2);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

转载于:https://www.cnblogs.com/lihongjunjava/p/8572351.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值