Insert values into table by the event handler - c#

I have connected my local database created by sql server with my project in visual studio (C#). Now I wish to enter the data given in the text field by the user in to my database. Here is what i have tried to do
private void Button_AddCustomer_Click(object sender, EventArgs e)
{
try
{
//SqlConnection objsqlconn = new SqlConnection(conn);
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" +
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("INSERT INTO
Customer(PhoneNumber,MobileNumber,Address) VALUES (a, b, c)", myConnection);
objcmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
It throws an exception saying that invalid column name a,invalid column name b,invalid column name c. Whats the problem and how do I get input from the user into my database using insert query ? I am working on visual studio C# and the local database was created by using ms sql.

Replace
VALUES (a, b, c)
with
VALUES (' + textBox1.value + (other text area) + ')'
Check the input before the query anyway!
Ok
SqlCommand objcmd = new SqlCommand("INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('" + PhoneNumber.Text + "', '" + MobileNumber.Text + "', '" + Address.Text + "')", myConnection);

You need enclose string types within single quotes.
Try This:
INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('a','b','c')
Suggestion: Your query is open to sql injection attacks please use Parameterised queries to avoid them.
Try This: Using Parameterised Queries.
private void Button_AddCustomer_Click(object sender, EventArgs e)
{
try
{
//SqlConnection objsqlconn = new SqlConnection(conn);
SqlConnection myConnection = new SqlConnection(
"Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;"
+ "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("INSERT INTO
Customer(PhoneNumber,MobileNumber,Address) VALUES
(#phonenumber,#mobilenumber,#address)", myConnection);
objcmd.Parameters.AddWithValue("#phonenumber",TextBox1.Text);
objcmd.Parameters.AddWithValue("#mobilenumber",TextBox2.Text);
objcmd.Parameters.AddWithValue("#address",TextBox3.Text);
objcmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}

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

Getting error SqlException was unhandled by user code

I'm creating a Registration form for new user sign up. Im getting the following error. I searched for solution on google, but none of them helped me.
Error : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
Could you please help me out with this?
Code :
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label1.Text = "User Name is Already Exist";
}
else
{
Label1.Text = "UserName is Available";
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
String str = "Insert into regform values ( '" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Session["name"] = TextBox1.Text;
Response.Redirect("Default.aspx");
con.Close();
}
}
Your connection string seems off
Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Using the AttachDbFilename=... element indicates you're using SQL Server Express, but the Express default installation would be using the SQLEXPRESS instance name - so your connection string should be
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Have you tried with this connection string? Any luck?
If that doesn't work - can you make sure what edition of SQL Server you have installed? Connecting to it in Management Studio - what do you use as server name?? And if you're connected - what does SELECT ##Version return?
utilize this example taken from Retrieving Data Using a DataReader
you will see quickly where you are making the slight code mistake
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
change your code here
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
Either create a Property or even better a Stored Procedure
The exception suggests that your connection string is wrong.
Isn't Initial Catalog=InstanceDB missing from your connection string? Where InstanceDB is the name of your database.
Use command parameters! If you don't, you will face several issues:
You will be threatened by SQL injection attacks!
You will have to deal with the special handling of null entries.
You will have to escape quotes in strings.
You will have to use the right formatting for date values.
Lengthy string concatenations look ugly.
SqlCommand cmd = new SqlCommand(
"SELECT * FROM regform WHERE username = #usr", con);
cmd.AddWithValue("#usr", TextBox1.Text);
Do the same for the insert statement.

C# project runs with no errors but doesn't add anything in the database?

I am trying to add records into my C# project and it runs with no errors but it doesn't add anything in the database:
private void saveBtn_Click(object sender, EventArgs e)
{
if (admNo.Text != "" & session.Text != "" & name.Text != "")
{
SqlConnection cn = new SqlConnection("Data Source=C:\\Users\\Divya Pathak\\Documents\\Visual Studio 2012\\Projects\\SchoolRecord\\SchoolRecord\\Database1.sdf");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.CommandText = "insert into addNew (no,session,name) values ('" + admNo.Text + "', '" + session.Text + "', '" + name.Text + "')";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record inserted successfully", "mission successfull");
}
}
Could someone please advise why?
you need to set cm.Connection as cn
cm.Connection =cn;
OR
using (var cn = new SqlCeConnection("connection string"))
using (var cmd = new SqlCeCommand("insert addNew (no,session,name) values (#no,#session,#name)", cn))
{
cmd.Parameters.AddWithValue("#no", admNo.Text);
cmd.Parameters.AddWithValue("#session", session.Text);
cmd.Parameters.AddWithValue("#name", name.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
This will help you to write the correct connection string for SQL CE
You have four mistakes:
You never associate the connection with the command
You're connecting to a Sql Server Compact database using the full Sql Server provider (you should be using the SqlCe namespace:
You're building your query using unsafe string concatenation instead of query parameters. Fix this!
Your connection won't be closed if an exception is thrown, which can ultimately lock you out of your database. You need to close the connection as part of a finally block, and the easiest way to do this is with a using block.
.
using (var cn = new SqlCeConnection("connection string here"))
using (var cmd = new SqlCeCommand("insert into addNew (no,session,name) values (#no,#session,#name)", cn))
{
//guessing at column lengths:
cmd.Parameters.Add("#no", SqlDbType.Int).Value = int.Parse(admNo.Text);
cmd.Parameters.Add("#session", SqlDbType.NVarChar, 100).Value = session.Text;
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 60).Value = name.Text;
cn.Open();
cmd.ExecuteNonQuery();
}

SQL Insert not working

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

Object reference not set to an instance of an object. Please Help to solve error

I am new to C#.
Kindly tell me what`s wrong with this code. I am inserting data in data base using two input fields EndValueTextBox and StartValueTextBox .
I am receiving following error. "Object reference not set to an instance of an object"
private void buttonSave_Click(object sender, EventArgs e)
{
connection = new System.Data.SqlClient.SqlConnection();
da = new SqlDataAdapter();
try
{
connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,"Connection String");
}
try
{
connection.Open();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
//SqlDataAdapter da = new SqlDataAdapter(query, connString);
da.InsertCommand.CommandText = sql;
da.InsertCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}
Your SqlDataAdapter is never assigned a connection to execute the query on. You need to associate the SqlConnection with the SqlDataAdapter during or after construction.
This line da.InsertCommand.CommandText = sql; has to be in that way:
da.InsertCommand = new SqlCommand(sql);
At what point you are the exception? Probably those line
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
SqlDataAdapter da = new SqlDataAdapter();
string connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
SqlConnection connection = new SqlConnection(connetionString);
try {
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Here's a minor rewrite of your code (not tested) that should take care of the SqlDataAdapter not having the connection object assigned and also demonstrates how to use parameterized queries to help defend against SQL Injection attacks:
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
// The using block will automatically dispose of your connection when
// the block is exited and is considered standard practice.
using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";))
{
SqlDataAdpter da = new SqlDataAdapter();
connection.Open();
// Assign the SqlConnection object to the SqlDataAdapter
da.Connection = connection;
// Parameterize the query as shown below
string sql = "INSERT INTO TBLWORKERS(first_name, last_name) VALUES(#first_name, #last_name)";
da.InsertCommand.CommandText = sql;
// Add the values for the parameters
da.InsertCommand.Parameters.Add("#first_name", SqlDbType.NVarChar, 25, StartValueTextBox.Text);
da.InsertCommand.Parameters.Add("#last_name", SqlDbType.NVarChar, 25, EndValueTextBox.Text);
// Execute the query - rows will have the number of rows
// affected. should be 1 in this case if succesful
int rows = da.InsertCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}

Categories

Resources