C# and Access database doesn't insert/save my data - c#

I wrote an application with C# and MS Access. I have my form login which it works. OK. And I have an insert statement which does not throw any error, but everything I enter into my textbox doesn't get inserted into my database, and when I want to make an update, it returns the same as insert statement, I mean no error, but the row is not inserted or updated.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void validateaddmember_button_Click(object sender, EventArgs e)
{
addmember.Visible = false;
MemoryStream ms = new MemoryStream();
pictureBox4.Image.Save(ms, pictureBox4.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],[Password],[Function],[Role],[Registerdata],[Personaldescription],[Phonenumber],[Picture]) VALUES(#f,#l,#e,#p,#fu,#r,#reg,#per,#ph,#pic) ";
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
cmd.Parameters.AddWithValue("#l", lastname_textbox.Text);
cmd.Parameters.AddWithValue("#e", email_textbox.Text);
cmd.Parameters.AddWithValue("#ph", phone_textbox.Text);
cmd.Parameters.AddWithValue("#fu", function_textbox.Text);
cmd.Parameters.AddWithValue("#r", role_dropbox.selectedValue);
cmd.Parameters.AddWithValue("#reg", DateTime.Now.ToString("dd-MM-yyyy HH: mm:ss"));
cmd.Parameters.AddWithValue("#per", richTextBox1.Text);
cmd.Parameters.AddWithValue("#p", repeatpassword_textbox.Text);
cmd.Parameters.AddWithValue("#pic", a);
cmd.ExecuteNonQuery();
con.Close();
}
And here I have in other form my update.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void bunifuFlatButton1_Click(object sender, EventArgs e)//login method
{
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd2 = new OleDbCommand();
cmd2.Parameters.Clear();
cmd2.Connection = con;
cmd2.CommandText ="update [team] set [Numberoflogin] = [Numberoflogin] + 1 where [Email]=#LEMAIL";
cmd2.Parameters.AddWithValue("#LEMAIL", materialSingleLineTextField1.Text);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}

Along with marc_s's important note -- you switched phone and password, make sure you fix that -- you only need # in the sql string. So not
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
but
cmd.Parameters.AddWithValue("Firstname", firstname_textbox.Text);
Use the field name (Firstname). #f is just a marker. With Access, you could write the sql string like so:
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],
[Password],[Function],[Role],[Registerdata],[Personaldescription],
[Phonenumber],[Picture]) VALUES(?,?,?,?,?,?,?,?,?,?)";
so when you add the parameter value, use the field name.
You could also open the connection right before cmd.ExecuteNonQuery();, like your update form.

Related

SqlCommand update doesn't update/insert

I don't understand why this code doesn't update my SQL Server table data:
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["devbuild"].ConnectionString;
public void Lastlogin()
{
SqlConnection con = new SqlConnection(stringcon); //CONNECTION
SqlCommand cmd2 = new SqlCommand();
cmd2.Parameters.Clear();
cmd2.Connection = con;
cmd2.CommandText = "update dbo.team set lastlogin=GETDATE() where email=#email";
cmd2.Parameters.AddWithValue("#email", emailtextbox.Text);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
When I press the button "login button", nothing happens, absolutely nothing error, nothing updates..
Call function from button.
private void loginbutton_Click(object sender, EventArgs e)
{
Lastlogin();
}
Display the sqlstri goed cmd2.commandtext
Check if it's what you expected
The problem should be your where clause
Your parameters has to be exact the same as the email field

Save a picture into database without binding source

I tried to save a picture into database using Sqlcommand . When I save , there is an exception throw said " Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query."
here is the code:
private void btn_save_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd1= new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
string squ1;
squ1 = "INSERT INTO Customer (cus_name, cus_address, cus_Image)Values('" + textBox1.Text + "' , '" + textBox2.Text + "', '"+pictureBox1 .Image +"');";
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
cmd1.Connection = con;
cmd1.CommandText = squ1;
cmd1.ExecuteNonQuery();
con.Close ();
}
// the browser button to get a picture
private void btn_browseImage_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog () == DialogResult .OK )
{
pictureBox1.ImageLocation = f.FileName;
}
You have to pass the image data as a varbinary parameter to the query:
using (var con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30"))
using (var cmd1 = new SqlCommand("INSERT INTO Customer (cus_name, cus_address, cus_Image)Values(#name, #address, #image);", con))
{
var imageData = new MemoryStream();
pictureBox1.Image.Save(imageData, pictureBox1.Image.RawFormat);
cmd1.Parameters.AddWithValue("#name", textBox1.Text);
cmd1.Parameters.AddWithValue("#address", textBox2.Text);
cmd1.Parameters.Add("#image", SqlDbType.VarBinary).Value = imageData.ToArray();
con.Open();
var result = cmd1.ExecuteNonQuery();
}
And you should really read up on how to use SqlCommand to avoid future SQL injection.
The statement '"+pictureBox1.Image +"' will actually call pictureBox1.Image.ToString() which is not the binary content of the image. Use SqlParameters to add your binary data. You can find a solution here...

How to insert value from gridview into database

I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}

What is the optimal / standard method of using a sql connection?

protected void populateDataGrid()
{
string connectionString = configurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string command = "select * from student";
SqlDataAdapter dataAdapter = new SqlDataAdapter(command, connectionString);
DataSet data = new DataSet();
dataAdapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (studentID, studentFirstName, studentLastName)
VALUES (" + TextID.Text + ", '" + TextFirstName.Text + "', '" + TextLastName.Text + "')";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
The first function gets all the table data and dumps it to a gridview.
The second function takes input and inserts it into the database.
How can these functions be condensed or simplified?
How can these functions be condensed or simplified?
I would focus on correctness before simplification. Currently I can see at least two problems with the code:
You should absolutely use parameterized SQL instead of putting the values into the SQL itself. Your current code is prone to SQL injection attacks.
You should use using statements so that connection and command are both closed automatically even if exceptions are thrown.
Then in terms of simplification:
You can use the SqlCommand constructor which takes the text and connection - the type defaults to Text anyway.
I would personally try to separate the UI code from the storage code, at least for a non-trivial project. You should look at ASP.NET MVC, at least to get some idea of separation, even if you don't change to start using it.
In Button2_Click(object sender, EventArgs e) method , you need to use parametrized query to avoid SQL Injection.
That is the standard way.
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (
studentID, studentFirstName, studentLastName
) VALUES (
#studID, #FName, #LName
)";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Parameters.AddWithValue("#studID", TextID.Text);
cmd.Parameters.AddWithValue("#FName", TextFirstName.Text);
cmd.Parameters.AddWithValue("#LName", TextLastName.Text);
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
}
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
Hope Its Helpful.

C# Windows Form App With Ms Access Failed to Insert Data

i know this topic is already discuss many time, but i still dont get my problem solved..
ok, i have a form to insert registration data into MS Access Database (2007), but my code doesnt insert data into database, and there are no errors,
here is the code:
OleDbConnection cn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb");
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
private void btnSave_Click(object sender, EventArgs e)
{
string idCard = this.txtID.Text;
string name = this.txtName.Text;
DateTime dateBirth = this.dateEdit1.DateTime;
cn.Open();
cmd.CommandText = "Insert into tb_reg (id, name, dateBirth, blood_type) Values(#id,#name,#dateBirth)";
cmd.Parameters.AddWithValue("#id", idCard);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#dateBirth", dateBirth.ToString());
adapter.InsertCommand = cmd;
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Succesfully added");
else
MessageBox.Show("try again");
cn.Close();
}
the message box always show "successfully added".
I had something like this in a project of mine. Maybe it works for you:
string insertString = string.Format(CultureInfo.InvariantCulture, "INSERT INTO tb_reg VALUES ('{0}', '{1}', '{2}', {3})", idCard, name, dateBirth, blood_type);
OleDbCommand cmd = new OleDbCommand(insertString, new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb"));
cmd.Connection.Open();
int numberAdded = cmd.ExecuteNonQuery();
if (numberAdded < 1)
{
//do something, the data was not added
}
else
{
//be happy :)
}
cmd.Connection.Close();
As I said, that worked for me.
The OleDB provider does not support named parameters. Change your SQL to
cmd.CommandText = #"Insert into tb_reg (id, name, dateBirth, blood_type)
Values(?,?,?,?)";
You can name the parameters when you create them, but it will assign them to the ? placeholders in the order that they are added to the command.
Also note that you're missing a parameter for blood_type.
Whatever you do, DON'T change to use string concatenation. It open the door for SQL Injection attacks.

Categories

Resources