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