SQL Insert not working - c#

When the event Button is pressed nothing updates in the SQL Table and no errors display.
protected void SubmitBTN_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Matt\Documents\coffeeShop.mdf;Integrated Security=True;Connect Timeout=30");
String coffeeName = NameTXT.Text;
String coffeeGrid = GrindTXT.Text;
String coffeeOrigin = OriginTXT.Text;
String coffeePrice = PriceTXT.Text;
String coffeeQty = QuantityTXT.Text;
String coffeeRRP = RRPTXT.Text;
SqlCommand comm = new SqlCommand("INSERT INTO Table (coffeeName, coffeeGrid, coffeeOrigin, coffeePrice, coffeeQty, coffeeRRP) VALUES ('%" + coffeeName + "%','%" + coffeeGrid + "%','%" + coffeeOrigin + "%','%" + coffeePrice + "%','%" + coffeeGrid + "%','%" + coffeeQty + "%','%" + coffeeRRP + "%' ", conn);
conn.Open();
//SqlDataReader reader = comm.ExecuteReader();
//lblDBData.Text += "<table border=0>";
//while (reader.Read())
//{
// lblDBData.Text += "<tr>";
// lblDBData.Text += "<td>" + reader["coffeeName"] + "</td>";
// lblDBData.Text += "</tr>";
//}
//lblDBData.Text += "</table>";
//reader.Close();
conn.Close();
}
Any advice would be much appreciated, Many thanks

Add:
comm.ExecuteNonQuery();
After:
conn.Open();
By the way, you would want to use parameters instead of " + parameter + " on query to avoid sql injection. Read this:
http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06

You need to execute the command as;
conn.Open(); //Open the connection to the database
comm.ExecuteNonQuery(); //This line does the insert
conn.Close(); //Close the connection once your command executed.
Also think about parameterised queries and to open connection object within a using block as a good practice to avoid leaving connection objects open.
Ex;
using(SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = new SqlCommand("your query string with #para", conn);
cmd.Parameters.AddWithValue("#para", "value");
conn.Open();
cmd.ExecuteNonQuery();
}

When you executes a Transact-SQL statement, the correct way is:
private const string connection = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Matt\Documents\coffeeShop.mdf;Integrated Security=True;Connect Timeout=30";
protected void SubmitBTN_Click(object sender, EventArgs e)
{
string query = "INSERT INTO Table (coffeeName, coffeeGrid, coffeeOrigin, coffeePrice, coffeeQty, coffeeRRP) VALUES (#name, #grid, #origin, #price, #qty, #rrp)";
using(SqlConnection conn = new SqlConnection(connection))
using(SqlCommand command = new SqlCommand(query, connection))
{
String coffeeName = NameTXT.Text;
String coffeeGrid = GrindTXT.Text;
String coffeeOrigin = OriginTXT.Text;
String coffeePrice = PriceTXT.Text;
String coffeeQty = QuantityTXT.Text;
String coffeeRRP = RRPTXT.Text;
command.Parameters.AddWithValue("#name", coffeeName);
command.Parameters.AddWithValue("#grid", coffeeGrid);
command.Parameters.AddWithValue("#origin", coffeeOrigin);
command.Parameters.AddWithValue("#price", coffeePrice);
command.Parameters.AddWithValue("#qty", coffeeQty);
command.Parameters.AddWithValue("#rrp", coffeeRRP);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (SqlException Ex)
{
console.WriteLine( "Error message: " + Ex);
}
finally
{
command.Connection.Close();
}
}
}

You can't read an insert statement. You have to use comm.executeNonQuery() to execute the insert command, then make a new select statement to read the data

You need to execute the SQL command. Before closing the connection, add this:
comm.ExecuteNonQuery();
For an example, see MSDN:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

Related

How can I insert and save data into database using Visual Studio and C#?

public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can I insert and save data into the database using Visual Studio and C#?
This code throws an error. Anyone please give the suggestion to me to solve the error.
image description
At first make sure your the data type of different column of customer table.
Then make sure what type of data you have to save for combobox.
you have to get the selected value from your Combobox. combobox1,combobox2,combobox3 retuns only the class name
System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
You can follow this example
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query):
Specifically, you don't need a reader for an insert statement as it doesn't return a result set.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var sql = "insert into dbo.customer ...";
using (var con = new SqlConnection(ss))
{
var cmd = new SqlCommand(sql , con);
con.Open();
cmd.ExecuteScalar();
MessageBox.Show("Welcome to our gym");
}
}
Hi check that customer table is available in gym Database.
else try this link
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(#name,#weight,#height,#add_class,#gender,#fees)", con);
cmd.Parameters.AddWithValue("name", this.textBox1.Text);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I found that your connection string declaration is wrong
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
need to update like below
public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";
Data source will be not be D, It should be Server name.
enter image description here

Retrieve Database values and show them on form using SQLDataReader

I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!

The error says "The ConnectionString property has not been initialized" in c#

this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}

SQLite and delete command

bool ret = false;
try
{
SQLiteConnection sqlConn = new SQLiteConnection("Data Source=" + m_dbName);
sqlConn.Open();
SQLiteCommand sqlComm = sqlConn.CreateCommand();
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name="+name+"";
SQLiteDataAdapter sqlAdapter = new SQLiteDataAdapter(sqlComm);
if (null == sqlAdapter)
{
ret = false;
}
else
{
ret = true;
}
sqlConn.Close();
return ret;
}
catch (SQLiteException sqlEx)
{
Console.WriteLine(sqlEx.Message);
return false ;
}
I have that code to delete a row in an sqlite database, but nothing is done after I click the delete button.
Instead of using a DataAdapter you could just execute the command directly:
using(SQLiteConnection sqlConn = new SQLiteConnection("Data Source=" + m_dbName))
{
sqlConn.Open();
//create command
sqlCommand.ExecuteNonQuery();
}
You shouldn't swallow any exceptions that get thrown from the ExecuteNonQuery method unless you can sensibly handle them. You should use parameterised queries instead of manually creating the queries by concatenating strings. You should also make sure you close the connection after you have finished using it as shown.
Try with single quotes:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name='"+name+"'";
Have you tried using like instead of =
inside the query:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name="+name+""
as this:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name like "+name+""
using (SQLiteCommand com = new SQLiteCommand(con))
{
com.CommandText = "DELETE FROM " + szTablename + " WHERE name='" + name + "';";
com.ExecuteNonQuery();
com.Dispose();
}

How to use UPDATE in ado net

I need to perform an update in a table(Homework). But it is not just replacing an old value with a new one; to the already existing value in the column i have to add(SUM) the new value(the column is of type int).
This is what i did so far but i am stuck:
protected void subscribeButton_Click(object sender, EventArgs e)
{
string txtStudent = (selectedStudentLabel.Text.Split(' '))[0];
int studentIndex = 0;
studentIndex = Convert.ToInt32(txtStudent.Trim());
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Trusted_Connection=True;User Instance=yes");
conn.Open();
string sql2 = "UPDATE student SET moneyspent = " + ?????? + " WHERE id=" + studentIndex + ";";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
try
{
conn.Open();
myCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}
}
What should i add intead of ??? to achieve my goal?
Is it possible to do it this way? I want to avoid using to many queries.
If i understand you correctly (i'm not sure i do) you want something like this:
string sql2 = "UPDATE student SET moneyspent = moneyspent + #spent WHERE id=#id";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
myCommand2.Parameters.AddWithValue("#spent", 50 )
myCommand2.Parameters.AddWithValue("#id", 1 )
Notice how i've used parameters and not string concatenation, very important!!

Categories

Resources