如何在Java程序中访问mysql数据库中的数据并进行简单的操作
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();
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询