Insert Values into database - c#

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;
}

Related

c# mysql unable to output query to a textbox

here is my code:
private void searchInDatabase()
{
MySqlConnection c = new MySqlConnection("datasource=localhost; username=root; password=123456; port=3306");
MySqlCommand mcd;
MySqlDataReader mdr;
String query;
try
{
c.Open();
query = "SELECT * FROM test.classmates WHERE first_name ='"+searchName.Text+"'";
mcd = new MySqlCommand(query, c);
mdr = mcd.ExecuteReader();
if(mdr.Read())
{
firstName.Text = mdr.GetString("first_name");
middleName.Text = mdr.GetString("middle_name");
lastName.Text = mdr.GetString("last_name");
age.Text = mdr.GetString("age");
}
else
{
MessageBox.Show("Result Not Found");
}
}
catch(Exception error)
{
MessageBox.Show("Error: "+error.Message);
}
finally
{
c.Close();
}
}
I would like to ask for a help if I have missed on anything or I am doing it wrong. If you have free time, I will much appreciate it if you will comment the perfect way to do I implement this problem: I want to get data from MySQL then put it in a textbox.
According to MSDN you need to pass the column number as parameter
public override string GetString(int i)
So try to pass the column number (starts from 0) of your column name. Assuming the first_name is the first column of your table then
firstName.Text = mdr.GetString(0);
UPDATE
Try to use MySqlConnectionStringBuilder
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "serverip/localhost";
conn_string.UserID = "my_user";
conn_string.Password = "password";
conn_string.Database = "my_db";
MySqlConnection conn = new MySqlConnection(conn_string.ToString();
First of all look at this sample of connection string and change your connection string:
'Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPasswor;'
If connection is OK send erorr message or full exception.

Error inserting a record and retrieving the autonumeric ID with OleDb

I am trying to make an oledb connection to an Access database to insert a new record and retrieving the key generated all at once. The code is this:
private static int createUser(OleDbConnection accessConn)
{
try
{
accessConn.Open();
//DbCommand also implements IDisposable
using (OleDbCommand cmd = accessConn.CreateCommand())
{
//create command with placeholders
cmd.CommandText =
"INSERT INTO EmployeeFiles " +
"([FirstName], [LastName], [JobTitleID], [SecurityLevel], [RowGUID])" +
"VALUES(#FirstName, #LastName, #JobTitleID, #SecurityLevel, #RowGUID)";
//Set Parameters
string FirstName = "Dick";
string LastName = "Tracy";
int JobTitleID = 11;
string SecurityLevel = "1";
string RowGUID = "{" + Guid.NewGuid() + "}";
//add named parameters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#FirstName", FirstName),
new OleDbParameter("#LastName", LastName),
new OleDbParameter("#JobTitleID", JobTitleID),
new OleDbParameter("#SecurityLevel", SecurityLevel),
new OleDbParameter("#RowGUID", RowGUID)
});
int userId = 0;
//Add #EmployeeID to the params collection and then retrieve it with Value
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
userId = (int)cmd.Parameters["#EmployeeID"].Value;
//userId = (int)cmd.ExecuteScalar();
Console.WriteLine("user created successfully: {0}", deliveryId);
return userId;
}
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed creating the user.\n{0}", ex.Message);
return 0;
}
finally
{
accessConn.Close();
}
}
And when I run the code it throws this error:
System.Data.OleDb.OleDbDataAdapter internal error: invalid parameter accessor: 9 BADBINDINFO
I'm pretty sure the problematic line is this:
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Direction = ParameterDirection.Output;
And I just don't get where is the mistake.
If I comment that and the next two lines, and uncomment this:
userId = (int)cmd.ExecuteScalar();
It throws the error: Object reference not set to an instance of an object
Is there a way to get this working with OleDbParameter? So far I'm being forced to make the insert and then a select to get the key generated.
I appreciate any suggestion.

exception "Input string was not in a correct format"

I am trying to associate adminID(which is foriegn key) with my table Media. I retrieve the adminID, but when I convert it to int it throw exception "Input string was not in a correct format".
void Insert(string name, int size, string path)
{
SqlConnection connec = new SqlConnection(ConfigurationManager.ConnectionStrings["BloodDonorRegistrationConnectionString"].ConnectionString);
string VidInsertQuary = "insert into Media(AdminID,Date,Time,Content,FileName,FilePath,TopicTittle,TopicDescr) values (#ad,#dt,#tm,#cc,#Fname,#Fpath,#TpTittle,#TpDes)";
string AdminID = "select AdminID from Admin where Email='" + Session["UserID"]+"'";
try
{
int tempid = 0;
SqlCommand com2 = new SqlCommand(AdminID, connec);
tempid = Convert.ToInt32(com2.ToString());
SqlCommand com = new SqlCommand(VidInsertQuary, connec);
connec.Open();
com2.Parameters.AddWithValue("#ad",tempid);
com.Parameters.AddWithValue("#dt", DateTime.Now.Date);
com.Parameters.AddWithValue("#tm", DateTime.Now.TimeOfDay);
com.Parameters.AddWithValue("#cc", size);
com.Parameters.AddWithValue("#Fname", name);
com.Parameters.AddWithValue("#Fpath", path);
com.Parameters.AddWithValue("#TpTittle",TextBoxTittle.Text);
com.Parameters.AddWithValue("#TpDes",TextBoxDescription.Text);
com.ExecuteNonQuery();
Response.Redirect("AdminVideoUpload.aspx");
}
catch (Exception ex)
{
string exp = "Problem occured";
Response.Write(exp + ex.ToString());
}
finally
{
connec.Close();
}
}
com2.ToString() has nothing to do with the query result, and is not a number.
You want .ExecuteScalar(), which will execute the query and return the first cell of the result.
Here
SqlCommand com2 = new SqlCommand(AdminID, connec);
you have defined a sql command. You haven't requested it's execution.
So here you don't have any result to convert it into an int:
tempid = Convert.ToInt32(com2.ToString());
Actually, the com2.ToString() will return the string representation of the com2 object whose type is of SqlCommand.
In order you solve your problem, you could try this:
tempid = Convert.ToInt32(com2.ExecuteScalar());
or this:
tempid = (Int32)com2.ExecuteScalar();
I had done this earlier and when I try this exception arises..
"System.Data.SqlClient.SqlException (0x80131904): Must declare the
scalar variable "#ad"."
This is another problem in your code, it has nothing to do with the above.
Actually, this
com2.Parameters.AddWithValue("#ad",tempid);
should be rewritten to this:
com.Parameters.AddWithValue("#ad",tempid);
The com2 is not a parameterized sql query. Not being it doesn't mean it shouldn't be. You should declare oly paramterized queries in order you avoid the danger of sql injections.

Input string was not in a correct format

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;

What's wrong with my IF statement?

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].

Categories