System.Data.SqlClient.SqlException: - Must declare the scalar variable.
public string testquery(string Transaction, List<string> columns, List<object> data, string tableName)
{
var strCol = string.Join(",", columns);
var strParam = string.Join(",", columns.Select(r => "@" + r));
var sql = "INSERT INTO [" + tableName + "] (" + strCol + ") VALUES (" + strParam + ")";
SqlConnection con = new SqlConnection(_conString);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText = sql;
for (int i = 0; i < columns.Count; i++)
{
command.Parameters.AddWithValue(strParam[i].ToString(), data[i]);
}
command.CommandType = CommandType.Text;
if (command.ExecuteNonQuery() > 0)
{
con.Close();
return "SUCCESS";
}
else
{
con.Close();
return "Fail";
}
}
The above function is called in page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> columns = new List<string>() { "u_ip" };
List<object> data = new List<object>() { 110654965406 };
String tableName = "Newuser";
testquery(null, columns, data, tableName);
}
}