1. ホーム
  2. Java

java.sql.SQLException: executeQuery()でデータ操作文を発行できません。

2022-02-09 16:17:26

1. エラーの説明

java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:924)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:870)
	at com.mysql.jdbc.StatementImpl.checkForDml(StatementImpl.java:472)
	at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1401)
	at com.you.sql.Student.commonMethod(Student.java:117)
	at com.you.sql.Student.insertStudent(Student.java:86)
	at com.you.sql.Student.main(Student.java:181)





<スパン 2. エラーの理由

public static void insertStudent()
	{
		StringBuffer sql = new StringBuffer();
		int j = 0;
		String str = "0";
		for(int i=5;i<1000;i++)
		{
			++j;
			if(i%2 == 0)
			{
				str = "0";
			}
			else
			{
				str = "1";
			}
			sql.append("insert into t_stu_info (").append(i).append(",").append(103+j+"").append(",")
			   .append("zhangsan"+(i-4)).append(",").append(str).append(",")
			   .append(Integer.parseInt(Math.round(Math.random()*10+20)+"")).append(",")
			   .append("123"+i);
		}
		
		commonMethod(sql.toString());
	}





/**
	 * 
	 * @Title:Student
	 * @Description:
	 * @param sqlStu
	 * @Date:Jun 11, 2015 12:25:56 AM
	 * @return :void 
	 * @throws
	 */
	public static void commonMethod(String sqlStu)
	{
		StringBuffer sql = new StringBuffer();
		sql.append(sqlStu);
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try 
		try
			try 
			{
				Class.forName(DRIVER_CLASS);
			} 
			catch (ClassNotFoundException e) 
			{
				e.printStackTrace();
			}
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
			stat = conn.createStatement();
			rs = stat.executeQuery(sql.toString());
			while(rs.next())
			{
				String stuId = rs.getString("stu_id");
				String stuName = rs.getString("stu_name");
				String stuSex = rs.getString("sex");
				String stuAge = rs.getString("stu_age");
				String stuPhone = rs.getString("stu_phone");
				System.out.println("Number: "+stuId+"----"+"Name: "+stuName+"----"+"Gender: "+stuSex+"-- "+"Age:"+stuAge+"----"+"Phone:"+stuPhone);
			}
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
		finally
		{
			if(rs ! = null)
			{
				try 
				{
					rs.close();
				} 
				catch (SQLException e) 
				{
					e.printStackTrace();
				}
			}
			if(stat ! = null)
			{
				try 
				{
					stat.close();
				} 
				catch (SQLException e) 
				{
					e.printStackTrace();
				}
			}
			if(conn ! = null)
			{
				try 
				{
					conn.close();
				} 
				catch (SQLException e) 
				{
					e.printStackTrace();
				}
			}
		}
	}





<スパン 3. ソリューション

     挿入操作の実行中に executeQuery メソッドが呼び出されたため、エラーが発生しました。挿入操作は executeUpdate メソッドを呼び出すべきでした。

     int result = stat.executeUpdate(sql.toString());