The reason for the syntax error is the extraneous trailing comma. If you examine the query in a debugger, it will show a string like INSERT INTO IP (IP) VALUES (N'127.0.0.1',
whereas it seems the intended query is INSERT INTO IP (IP) VALUES (N'127.0.0.1')
. So you simply need to remove that comma and add a close parenthesis for valid syntax.
There are other serious issues with the code that also need to be addressed. Most importantly, one should never use string concatenation or interpolation to specify SQL statement values. Instead, always use parameters for those values. Below is the corrected version. Note the SQL statement itself never changes, just the parameter value.
string sqlQuery = "INSERT INTO IP (IP) VALUES (@IP);";
using (SqlCommand command = new SqlCommand(sqlQuery, conn))
{
command.Parameters.Add("@IP", SqlDbType.VarChar, 15).Value = IPAddress;
command.ExecuteNonQuery(); //execute the Query
Console.WriteLine("Query Executed.");
}
Another issues is the UPDATE Statement. It has no WHERE clause so every row in the table will be updated. Furthermore, the purpose is not clear since the row with the same value was just inserted. That said, here's an example of a parameterized update query:
string sqlUpdateQuery = "UPDATE IP SET ExampleColumn = @ExampleValue WHERE IP = @IP;";
using (SqlCommand command = new SqlCommand(sqlUpdateQuery, conn))
{
command.Parameters.Add("@ExampleValue", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("@IP", SqlDbType.VarChar, 15).Value = IPAddress;
command.ExecuteNonQuery(); //execute the Query
Console.WriteLine("Query Executed.");
}
It is good you are employing using blocks to ensure objects are immediately disposed. Do the same for the SqlConnection object and other objects that implement IDisposable to avoid leaks.