I am trying to make a simple app that gets your IP address and stores it in a sql database 1
But I am getting a error saying
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
Here is my code:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Text;
namespace Test
{
public class GetIP
{
public static string GetIPAddress()
{
string content = File.ReadAllText(@"C:\Users\Home\source\repos\Test\Test\IP.txt");
string IPAddress = string.Empty;
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
bool infile;
foreach (IPAddress IP in Host.AddressList)
{
if (IP.AddressFamily == AddressFamily.InterNetwork)
{
IPAddress = Convert.ToString(IP);
}
}
if (content.Contains(IPAddress) == false)
{
var datasource = @"(localdb)\MSSQLLocalDB";//your server
var database = "IP"; //your database name
//your connection string
string connString = @"Data Source=" + datasource + ";Initial Catalog="
+ database + ";Persist Security Info=True;User ID=";
//create instanace of database connection
SqlConnection conn = new SqlConnection(connString);
//create a new SQL Query using StringBuilder
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append("INSERT INTO IP (IP) VALUES ");
strBuilder.Append($@"(N'{IPAddress}', ");
conn.Open();
string sqlQuery = strBuilder.ToString();
using (SqlCommand command = new SqlCommand(sqlQuery, conn)) //pass SQL query created above and connection
{
command.ExecuteNonQuery(); //execute the Query
Console.WriteLine("Query Executed.");
}
strBuilder.Clear(); // clear all the string
strBuilder.Append($"UPDATE IP SET IP = N'{IPAddress}'");
using (SqlCommand command = new SqlCommand(sqlQuery, conn))
{
int rowsAffected = command.ExecuteNonQuery(); //execute query and get updated row count
Console.WriteLine(rowsAffected + " row(s) updated");
}
/*FileStream fs = new FileStream(@"C:\Users\Home\source\repos\Test\Test\IP.txt", FileMode.Open, FileAccess.ReadWrite);
fs.Seek(0, SeekOrigin.Current);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(IPAddress);
sw.Close();
fs.Close();
infile = true;*/
}
return IPAddress;
}
}
class Program
{
static void Main(string[] args)
{
GetIP ip = new GetIP();
string ipadress = GetIP.GetIPAddress();
Console.WriteLine(ipadress);
Console.ReadKey(true);
}
}
}
The expectation pops up at :
command.ExecuteNonQuery();
Any help will be appreciated