I'm trying to make a simple application form were user can input data like 'reservationid', 'bookid', 'EmployeeID' and 'reservedate'. Its from my program Library System. 'reservationid' is an auto increment primary key while the rest are BigInt50, NVarChar50 and DateTime10 respectively. So I'm having this error: Input String was not in a correct format. It worked fine a while ago until I modified the 'reservationid' to auto increment so where did I go wrong? I've attached a sample of my code behind.
Any help would be greatly appreciated! Thanks in advance!
namespace LibraryManagementSystemC4.User
{
public partial class Reserving : System.Web.UI.Page
{
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["LibrarySystemConnectionString"].ConnectionString;
}
//string reservationid
private void ExecuteInsert(string bookid, string EmployeeID, string reservedate)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO BookReservation (reservationid, bookid, EmployeeID, reservedate) VALUES " + " (#reservationid, #bookid, #EmployeeID, #reservedate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("#reeservationid", SqlDbType.Int, 50);
param[0] = new SqlParameter("#bookid", SqlDbType.BigInt, 50);
param[1] = new SqlParameter("#EmployeeID", SqlDbType.NVarChar, 50);
param[2] = new SqlParameter("#reservedate", SqlDbType.DateTime, 10);
//param[0].Value = reservationid;
param[0].Value = bookid;
param[1].Value = EmployeeID;
param[2].Value = reservedate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert error";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (reservationidTextBox != null)
{
//reservationidTextBox.Text
ExecuteInsert(bookidTextBox.Text, EmployeeIDTextBox.Text, reservationidTextBox.Text);
ClearControls(Page);
}
else
{
Response.Write("Please input ISBN");
bookidTextBox.Focus();
}
{
//get bookid from Book Details and Employee PIN from current logged-in user
bookidTextBox.Text = DetailsView1.SelectedValue.ToString();
EmployeeIDTextBox.Text = HttpContext.Current.User.Identity.ToString();
}
}
public static void ClearControls(Control Parent)
{
if (Parent is TextBox)
{
(Parent as TextBox).Text = string.Empty;
}
else
{
foreach (Control c in Parent.Controls)
ClearControls(c);
}
}
}
}
If reservationid is auto incremented then remove it from your insert query
string sql = "INSERT INTO BookReservation ( bookid, EmployeeID, reservedate) VALUES (#bookid, #EmployeeID, #reservedate)";
also try
param[0].Value = Convert.ToInt64(bookid);
param[1].Value = EmployeeID;
param[2].Value = Convert.ToDate(reservedate);
after you made reservationid to autoincrement then you dont have to do like
string sql = "INSERT INTO BookReservation (reservationid, bookid, EmployeeID, reservedate) VALUES " + " (#reservationid, #bookid, #EmployeeID, #reservedate)";
remove reservationid to insert.
do like
string sql = "INSERT INTO BookReservation ( bookid, EmployeeID, reservedate) VALUES (#bookid, #EmployeeID, #reservedate)";
Its because you are not passing the reservationid an Integer value to your command parameters when it is not Auto Increment.
I can see from your code, that you have declared string reservationid, but you are not assigning it any value and secondly it should an integer value.
I know this is deeply necro-posted, but since it seems from Loupi's comment on 9Jun11 that he was still having problems, I'd post the actual answer. Bala's answer was what was still giving him the Input Type is not in a correct format error; using a Convert.ToInt64 statement in a value assignation was tripping it. Do the conversion in variables previous to assigning the parameter values and it works a charm. The most likely culprit is that bookid was some sort of non-zero empty string representation (blank quotes, a space, null, whatever).
Edit: A quick and easy one-line test that's relatively bulletproof:
long numAccountNum = Int64.TryParse(AccountNum, out numAccountNum) ? Convert.ToInt64(AccountNum) : 0;
Related
I trying to update a GridView using asp.net while updating I am passing the text box value but I am getting the above error.
Label l1 = g1.Rows[e.RowIndex].FindControl("idlbl") as Label;
TextBox t1 = g1.Rows[e.RowIndex].FindControl("typeText") as TextBox;
string orderType = t1.Text;
string Query = #"update app_order_master set order_amt=" + orderType + " where order_id=" + l1.Text;
MySqlCommand cmd = new MySqlCommand(Query);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
Try using parameters instead
Label l1 = g1.Rows[e.RowIndex].FindControl("idlbl") as Label;
TextBox t1 = g1.Rows[e.RowIndex].FindControl("typeText") as TextBox;
string orderType = t1.Text;
string order_id = l1.Text;
string Query = "update app_order_master set order_amt = #orderType where order_id = #order_id";
MySqlCommand cmd = new MySqlCommand(Query);
cmd.Parameters.Add("#orderType", orderType);
cmd.Parameters.Add("#order_id", order_id);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
Here is another example that might help you, a pointer that other developers have mentioned your original code is a probe to SQL injection if you bing search this, there are loads of examples that you can find of what SQL injection is. Here is my method that might assist you. A little code example to assist you.
public void updateProductTbl(string prodBrand, string description, decimal weight, decimal unitwholesaleprice, decimal unitretailprice, string prodImage, string location, string qrcode,
string barcode, string suppliercode, int unitinstock, int unitsonorder, int reorderlevel, bool discontinued, decimal unitofmeasure, string prodcategory, int OldValue)
{
query = #"update Product
SET
prod_band=#prodBrand
,prod_description=#description
,prod_weight=#weight
,prod_perUnitwholesalePrice=#unitwholesaleprice
,prod_perUnitRetailPrice = #unitretailprice
,prod_Image=#prodImage
,prod_location=#location
,prod_QRcode=#qrcode
,prod_barcode=#barcode
,prod_supplierFKCode=#suppliercode
,prod_unitsinstock=#unitinstock
,prod_unitsonorder=#unitonorder
,prod_reorderlevel=#reorderlevel
,prod_discontinued=#discontinued
,prod_unitofmeasure=#unittofmeasure
,prod_category=#prodcategory
where prod_rec_id=#OldValue";
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(query, myConn);
myCommand.Parameters.AddWithValue("#prodBrand", prodBrand);
myCommand.Parameters.AddWithValue("#description", description);
myCommand.Parameters.AddWithValue("#weight", weight);
myCommand.Parameters.AddWithValue("#unitwholesaleprice", unitwholesaleprice);
myCommand.Parameters.AddWithValue("#unitretailprice", unitretailprice);
myCommand.Parameters.AddWithValue("#prodImage", prodImage);
myCommand.Parameters.AddWithValue("#location", location);
myCommand.Parameters.AddWithValue("#qrcode", qrcode);
myCommand.Parameters.AddWithValue("#barcode", barcode);
myCommand.Parameters.AddWithValue("#suppliercode", suppliercode);
myCommand.Parameters.AddWithValue("#unitinstock", unitinstock);
myCommand.Parameters.AddWithValue("#unitonorder", unitsonorder);
myCommand.Parameters.AddWithValue("#reorderlevel", reorderlevel);
myCommand.Parameters.AddWithValue("#discontinued", discontinued);
myCommand.Parameters.AddWithValue("#unittofmeasure", unitofmeasure);
myCommand.Parameters.AddWithValue("#prodcategory", prodcategory);
myCommand.Parameters.AddWithValue("#OldValue", OldValue);
status = myCommand.ExecuteNonQuery(); // when ExecuteNonQuery method return 1 or 0 if it have saved to sql db
if (status > 0)
{
MessageBox.Show("Your Data has been updated", "Update Data", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch(Exception ex)
{
MessageBox.Show("SQL Error in Product Add method:"+ex.ToString(), "Warning Data not saved", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
myConn.Close();
}
}
Hope the abe gives you a good idea of how to go about SQl and passing params in a method.
I have a gridview and I want to checked line in insert but I see this error:
CommandText property has not been initialized.
I guess my mistake about strArrays. I'm working two days about it
How can I fixed?
StringBuilder stringBuilder = new StringBuilder(string.Empty);
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString.ToString());
SqlCommand sqlCommand = new SqlCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int type = 2;
CheckBox chkUpdate = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkSelect");
TextBox txtAmount = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtAmount");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = GridView1.Rows[i].Cells[1].Text;
GridView1.Rows[i].FindControl("txtLocation")).Text;
string text = this.GridView1.Rows[i].Cells[1].Text;
string[] strArrays = new string[] { "INSERT INTO [OrderCancel]
([OrderID],
[Message],
[Type],
[RelationProductID],
[Amount])
VALUES(" ,
Request.QueryString["o"] ,
",'" , txtWhy.Text ,
"',",type.ToString(),",
" , strID , "," ,
txtAmount.Text , ");" };
stringBuilder.Append(string.Concat(strArrays));
//append update statement in stringBuilder
stringBuilder.Append(string.Concat(strArrays));
}
}
try
{
try
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = stringBuilder.ToString();
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
catch (SqlException sqlException)
{
throw new Exception(string.Concat("Error in Updation",
sqlException.Message));
}
}
finally
{
sqlConnection.Close();
}
Your code could be cleaned up, you could do the following:
private readonly string dbConnection = "...";
private const string query = "... Column = #Column";
For the sake of brevity I've added ... which will correlate to your Connection String and your query with parameters.
var message = String.Empty;
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(query, dbConnection))
{
connection.Open();
command.CommandType = CommandType.Text;
command.Parameters.Add("#Column", SqlDbType.NVarChar).Value = message;
command.ExecuteNonQuery();
}
So that small snippet would be inside of a method, which would pass a model of the data in your Grid. Then when you pass a value from your Grid, then you would build your model and pass to the method which will write to your database.
Also, when you use a StringBuilder you will also need to call ToString(); to ensure that it is a string rather than a StringBuilder when your utilizing.
This error usually happens if you do not set the commandText property. looking at your code it looks like your stringbuilder variable is not getting set. have you tried putting a breakpoint inside your "chkUpdate.Checked" loop? if yes, can you post the sql that gets constructed in your loop
I have been using the following code to insert the values into the MySQL database. The code builds with no error message but as soon as I try to run the code it says:
MySql.Data.MySqlClient.MySqlException: Column 'name' cannot be null
Please tell me the error in my code.
Here is the insert function that i am using:
public int insert (int id, string name, string sname, int marks )
{
string connection= ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand com = new MySqlCommand("INSERT INTO Student_details(id,name,sname,marks) values(#id,#name, #sname, #marks)");
// com.Connection = com;
com.Connection = con;
con.Open();
//com.Parameters.Add("#id", id);
//com.Parameters.Add("#name", name);
//com.Parameters.Add("#sname", sname);
//com.Parameters.Add("#marks", marks);
com.Parameters.AddWithValue("#id", id);
com.Parameters.AddWithValue("#name", name);
com.Parameters.AddWithValue("#sname", sname);
com.Parameters.AddWithValue("#marks", marks);
//// com.Parameters.a
//com.ExecuteNonQuery();
int ret = Convert.ToInt32(com.ExecuteScalar());
return ret;
}
Can you rewrite your method with arguments validation? This will give you a +1 to your programming style. Plus you will know faster if the input does not follow an expected contract.
public int insert (int id, string name, string sname, int marks )
{
if(name == null) throw new ArgumentNullException("name");
...
}
Seems like you are passing a name parameter which is null.
Are you sure name is not null? You don't validate your params.
Hi i am using the simple following front end function to insert the value of data fields into the dataaccess layer class which has the function Insert()... please see to to it where i am going wrong........
try
{
DataAccessLayer dal = new DataAccessLayer();
int id = 23;
string name = "mayank";
string sname = "agarwal";
int marks = 34;
int a = dal.insert(id, name, sname, marks);
LblUserName.Text = a.ToString();
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
throw;
}
I have a form with a text box and button, such that when the user clicks the button, the specified name in the text box is added to a table in my sql database. The code for the button is as follows:
private void btnAddDiaryItem_Click(object sender, EventArgs e)
{
try
{
string strNewDiaryItem = txtAddDiaryItem.Text;
if (strNewDiaryItem.Length == 0)
{
MessageBox.Show("You have not specified the name of a new Diary Item");
return;
}
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES = ('" + strNewDiaryItem + "');";
cSqlQuery cS = new cSqlQuery(sqlText, "non query");
PopulateInitialDiaryItems();
MessageBox.Show("New Diary Item added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Unhandled Error: " + ex.Message);
}
}
The class cSqlQuery is a simple class that executes various T-SQL actions for me and its code is as follows:
class cSqlQuery
{
public string cSqlStat;
public DataTable cQueryResults;
public int cScalarResult;
public cSqlQuery()
{
this.cSqlStat = "empty";
}
public cSqlQuery(string paramSqlStat, string paramMode)
{
this.cSqlStat = paramSqlStat;
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
if (paramMode == "non query")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(cSqlStat, linkToDB))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
this.cScalarResult = (Int32)sqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public cSqlQuery(SqlCommand paramSqlCom, string paramMode)
{
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
paramSqlCom.Connection = linkToDB;
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(paramSqlCom))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
paramSqlCom.Connection = linkToDB;
this.cScalarResult = (Int32)paramSqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public string BuildConnectionString()
{
cConnectionString cCS = new cConnectionString();
return cCS.strConnect;
}
}
The class works well throughout my application so I don't think the error is in the class, but then I can't be sure.
When I click the button I get the following error message:
Incorrect syntax near =
Which is really annoying me, because when I run the exact same command in SQL Management Studio it works fine.
I'm sure I'm missing something rather simple, but after reading my code through many times, I'm struggling to see where I have gone wrong.
you have to remove = after values.
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES ('" + strNewDiaryItem + "');"
and try to use Parameterized queries to avoid Sql injection. use your code like this. Sql Parameters
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES (#DairyItem);"
YourCOmmandObj.Parameters.AddwithValue("#DairyItem",strNewDiaryIItem)
Remove the = after VALUES.
You do not need the =
A valid insert would look like
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Source: http://www.w3schools.com/sql/sql_insert.asp
Please use following:
insert into <table name> Values (value);
Remove "=", and also i would recommend you to use string.format() instead of string concatenation.
sqlText = string.format(INSERT INTO tblDiaryTypes (DiaryType) VALUES ('{0}'), strNewDiaryItem);"
I'm creating an auditting table, and I have the easy Insert and Delete auditting methods done. I'm a bit stuck on the Update method - I need to be able to get the current values in the database, the new values in the query parameters, and compare the two so I can input the old values and changed values into a table in the database.
Here is my code:
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
string[] fields = null;
string fieldsstring = null;
string fieldID = e.Command.Parameters[5].Value.ToString();
System.Security.Principal. WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string[] namearray = p.Identity.Name.Split('\\');
string name = namearray[1];
string queryStringupdatecheck = "SELECT VAXCode, Reference, CostCentre, Department, ReportingCategory FROM NominalCode WHERE ID = #ID";
string queryString = "INSERT INTO Audit (source, action, itemID, item, userid, timestamp) VALUES (#source, #action, #itemID, #item, #userid, #timestamp)";
using (SqlConnection connection = new SqlConnection("con string = deleted for privacy"))
{
SqlCommand commandCheck = new SqlCommand(queryStringupdatecheck, connection);
commandCheck.Parameters.AddWithValue("#ID", fieldID);
connection.Open();
SqlDataReader reader = commandCheck.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount - 1; i++)
{
if (reader[i].ToString() != e.Command.Parameters[i].Value.ToString())
{
fields[i] = e.Command.Parameters[i].Value.ToString() + "Old value: " + reader[i].ToString();
}
else
{
}
}
}
fieldsstring = String.Join(",", fields);
reader.Close();
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#source", "Nominal");
command.Parameters.AddWithValue("#action", "Update");
command.Parameters.AddWithValue("#itemID", fieldID);
command.Parameters.AddWithValue("#item", fieldsstring);
command.Parameters.AddWithValue("#userid", name);
command.Parameters.AddWithValue("#timestamp", DateTime.Now);
try
{
command.ExecuteNonQuery();
}
catch (Exception x)
{
Response.Write(x);
}
finally
{
connection.Close();
}
}
}
The issue I'm having is that the fields[] array is ALWAYS null. Even though the VS debug window shows that the e.Command.Parameter.Value[i] and the reader[i] are different, the fields variable seems like it's never input into.
Thanks
You never set your fields[] to anything else than null, so it is null when you are trying to access it. You need to create the array before you can assign values to it. Try:
SqlDataReader reader = commandCheck.ExecuteReader();
fields = new string[reader.FieldCount]
I don't really understand what your doing here, but if your auditing, why don't you just insert every change into your audit table along with a timestamp?
Do fields = new string[reader.FieldCount] so that you have an array to assign to. You're trying to write to null[0].