Avoid checkstyle magic number errors in JDBC queries
I'm having a group project in class. We're trying checkstyle
I'm very satisfied with Java, but I've never touched JDBC or done any database work before
I would like to know if there is an elegant way to avoid the wrong number errors in the preparation statement call, please consider:
preparedStatement = connect.prepareStatement("INSERT INTO shows " + "(showid,showtitle,showinfo,genre,youtube)" + "values (default,?,?);"); preparedStatement.setString(1,title); preparedStatement.setString(2,info); preparedStatement.setString(3,genre); preparedStatement.setString(4,youtube); result = preparedStatement.executeUpdate();
The setstring method is marked as a magic number. So far, I have just added about 3-10 numbers to the ignore list of magic numbers, but I wonder if there is a better way to insert these values into the statement I also ask you to make any other suggestions. Please note that seeing this code, I want to avoid developing any annoying habits, such as should I use statement or Preparedstatement? Will that make me refer to the list? Is that an ideal? Wait
thank you!
Solution
Create a practical method to do this:
public static void setValues(PreparedStatement preparedStatement,Object... values) throws sqlException { for (int i = 0; i < values.length; i++) { preparedStatement.setObject(i + 1,values[i]); } }
And use the following:
setValues(preparedStatement,title,info,youtube);
or
Object[] values = { title,youtube }; setValues(preparedStatement,values);
More "best practices" on basic JDBC coding can be found in this article
I hope this will help