Can not issue data manipulation statements with executeQuery()解决方案

MySQL数据库连接后执行表结构创建语句,java代码如下:

        String driver = "com.mysql.jdbc.Driver"; // 获取mysql数据库的驱动类
	String url = "jdbc:mysql://" + dataSource.getDataSourceIp() + ":" + dataSource.getDataSourcePort() + "/" + dataSource.getDataSourceName()
					+ "?characterEncoding=" + dataSource.getCharacterSet(); // 连接数据库
	String userName = dataSource.getDataSourceUser();// 连接mysql的用户名
	String password = dataSource.getDataSourcePwd();// 连接mysql的密码
	try {
		Class.forName(driver);
		Connection con = (Connection) DriverManager.getConnection(url, userName, password);
		String s = con.nativeSQL(sql);
		System.out.println(s);
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery(sql);
		while (rs.next()) {
			System.out.println(rs.getString(1) + "/t" + rs.getString(2));
		}
		rs.close();
		st.close();
		con.close();
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	} catch (SQLException e) {
		e.printStackTrace();
	}

报错信息如下:

Can not issue data manipulation statements with executeQuery()

经过调试,是因为如果执行create,update,insert的sql语句应该用statement的execute()方法,如果用的是statement的executeQuery()就会出现上诉问题

修改后的java代码如下:

String driver = "com.mysql.jdbc.Driver"; // 获取mysql数据库的驱动类
String url = "jdbc:mysql://" + dataSource.getDataSourceIp() + ":" + dataSource.getDataSourcePort() + "/" + dataSource.getDataSourceName()+ "?characterEncoding=" + dataSource.getCharacterSet(); // 连接数据库
String userName = dataSource.getDataSourceUser();// 连接mysql的用户名
String password = dataSource.getDataSourcePwd();// 连接mysql的密码
try {
	Class.forName(driver);
	Connection con = (Connection) DriverManager.getConnection(url, userName, password);
	String s = con.nativeSQL(sql);
	Statement st = con.createStatement();
	boolean result = st.execute(sql);
	st.close();
	con.close();
} catch (ClassNotFoundException e) {
	e.printStackTrace();
} catch (SQLException e) {
	e.printStackTrace();
}

 
  

你可能感兴趣的:(SQL)