Insert data to SQL using C# - c#

I keep on getting the problem
"An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.dll" "on
SDA.SelectCommand.ExecuteNonQuery();".
Whats the problem here?
SqlConnection con = new SqlConnection(#"Data Source=LAPTOP-LD5OK96E\SQLEXPRESS;Initial Catalog=TRANSACTION_RATE TABLE; Integrated Security=True");
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
String query = "INSERT INTO TRANSACTION_RATE TABLE (Trans_id,Transaction_type,Transact_rate,Transact_description) VALUES('" + textBox1.Text + "','" + textBox2.Text + "''" + textBox3.Text + "''" + textBox4.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Success!");

You have one stray TABLE keyword after your table's name, you need to remove it. as a second note, you need to be aware that this kind of string concatenation is avoided and it is open to SQL Injection attack:
String query = "INSERT INTO TRANSACTION_RATE (Trans_id,Transaction_type,Transact_rate,Transact_description) VALUES (#Trans_id, #Transaction_type,#Transact_rate, #Transact_description)";
SDA.SelectCommand.Parameters.Add("#Trans_id", SqlDbType.NVarChar, 50).Value = textBox1.Text;
SDA.SelectCommand.Parameters.Add("#Transaction_type", SqlDbType.NVarChar, 50).Value = textBox2.Text;
SDA.SelectCommand.Parameters.Add("#Transact_rate", SqlDbType.NVarChar, 50).Value = textBox3.Text;
SDA.SelectCommand.Parameters.Add("#Transact_description", SqlDbType.NVarChar, 50).Value = textBox4.Text;
In case your table was named in fact TRANSACTION_RATE TABLE you should escape the name like this:
INSERT INTO [TRANSACTION_RATE TABLE] ....

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

Data type mismatch in criteria expression(Convert.ToInt32(cmd.ExecuteScalar());)

I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());

how to do time stamping in access db using c#

private void button1_Click(object sender, EventArgs e)
{
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString =#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID)VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
mycon.Open();
command.Connection = mycon;
command.ExecuteNonQuery();
mycon.Close();
}
this is the code that I have written to insert some details in my access db. I want that this button click also add the date and time of click into a column in my db. I tried to directly add a function GetDate within INSERT but it failed to execute. Any suggestions?
I haven't tested this code, but it should get you started...
private void button1_Click(object sender, EventArgs e)
{
using OleDbConnection mycon = new OleDbConnection()
{
mycon.ConnectionString =#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Table1 (Emp_ID, Asset_ID, Date_Column) VALUES (?, ?, ?)";
command.Parameters.Add("#EmpID", OleDbType.VarChar, 80).Value = textBox1.Text;
command.Parameters.Add("#AssetID", OleDbType.VarChar, 80).Value = textBox2.Text;
command.Parameters.Add("#Timestamp", OleDbType.Date).Value = DateTime.Now;
command.Connection = mycon;
mycon.Open();
command.ExecuteNonQuery();
}
}
Add datetime column with default value of now
It can be done like the below
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

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.

Inserting values into a SQL Server database using ado.net via C#

I have created a simple program to insert values into the table [regist], but I keep getting the error
Incorrect syntax near ')'
on cmd.ExecuteNonQuery();:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact, " + ") VALUES (" + " #textBox1.Text, #textBox2.Text, #textBox3.Text, #textBox4.Text, #comboBox1.Text,#comboBox2.Text,#textBox7.Text" + ")", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
I am new to this and I am really confused.
As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.
Also: I would recommend to separate the click event handler from the actual code to insert the data.
So I would rewrite your code to be something like
In your web page's code-behind file (yourpage.aspx.cs)
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
InsertData(connectionString,
textBox1.Text.Trim(), -- first name
textBox2.Text.Trim(), -- last name
textBox3.Text.Trim(), -- user name
textBox4.Text.Trim(), -- password
Convert.ToInt32(comboBox1.Text), -- age
comboBox2.Text.Trim(), -- gender
textBox7.Text.Trim() ); -- contact
}
In some other code (e.g. a databaselayer.cs):
private void InsertData(string connectionString, string firstName, string lastname, string username, string password
int Age, string gender, string contact)
{
// define INSERT query with parameters
string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FirstName, #Lastname, #Username, #Password, #Age, #Gender, #Contact) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstName;
cmd.Parameters.Add("#Lastname", SqlDbType.VarChar, 50).Value = lastName;
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = userName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = password;
cmd.Parameters.Add("#Age", SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 50).Value = gender;
cmd.Parameters.Add("#Contact", SqlDbType.VarChar, 50).Value = contact;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
Code like this:
is not vulnerable to SQL injection attacks
performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)
Remove the comma
... Gender,Contact, " + ") VALUES ...
^-----------------here
Following Code will work for "Inserting values into a SQL Server database using ado.net via C#"
// Your Connection string
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
// Collecting Values
string firstName="Name",
lastName="LastName",
userName="UserName",
password="123",
gender="Male",
contact="Contact";
int age=26;
// Query to be executed
string query = "Insert Into dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FN, #LN, #UN, #Pass, #Age, #Gender, #Contact) ";
// instance connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// add parameters and their values
cmd.Parameters.Add("#FN", System.Data.SqlDbType.NVarChar, 100).Value = firstName;
cmd.Parameters.Add("#LN", System.Data.SqlDbType.NVarChar, 100).Value = lastName;
cmd.Parameters.Add("#UN", System.Data.SqlDbType.NVarChar, 100).Value = userName;
cmd.Parameters.Add("#Pass", System.Data.SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#Age", System.Data.SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", System.Data.SqlDbType.NVarChar, 100).Value = gender;
cmd.Parameters.Add("#Contact", System.Data.SqlDbType.NVarChar, 100).Value = contact;
// open connection, execute command and close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}

Categories

Resources