如何在Java程序中访问mysql数据库中的数据并进行简单的操作

2024-12-25 17:36:07
推荐回答(1个)
回答1:

添加驱动包//加载驱动Class.forName("com.mysql.jdbc.Driver"); //获取数据库连接String user = "root" ,password = "mysql",url="jdbc:mysql://localhost:3306/test??characterEncoding=utf8";Connection connection = DriverManager.getConnection(url, user, password); //增加String sql = "insert into t1(id,name) values(?,?)";PreparedStatement statement = connection.prepareStatement(sql);statement.setString(1, "123123123");statement.setString(2, "jdbc");System.out.println(statement.executeUpdate()); //查询sql = "select * from t1";Statement query = connection.createStatement();ResultSet rs = query.executeQuery(sql);while(rs.next()){System.out.println(rs.getString("id")+","+rs.getString("name"));} //修改sql = "update t1 set name = ? where id = ?";statement = connection.prepareStatement(sql);statement.setString(1, "java");statement.setString(2, "123123123");System.out.println(statement.executeUpdate()); //删除sql = "delete from t1 where id = ?";statement = connection.prepareStatement(sql);statement.setString(1, "123123123");System.out.println(statement.executeUpdate()); connection.close();