I have successfully created connection of database but now I'm having problem in insertion of data. Here is my code:
String Connection = null;
SqlConnection con;
SqlCommand cmd;
String sql = null;
Connection="Data Source=DELL\\SQLEXPRESS; initial Catalog= BSSE;Integrated Security=True";
con = new SqlConnection(Connection);
sql = "INSERT INTO Records (Roll_No,Name,Marks) VALUES (" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ");";
try
{
con.Open();
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
First, your SQL statement is incorrect. You are missing single quote between values field. Later, you build SQL statement by using string concatenation and this is dangerous because can be exposed to SQL Injection. Use Parameterized Query instead.
try
{
con.Open();
cmd = new SqlCommand("INSERT INTO Records (Roll_No,Name,Marks) VALUES (#rollNo, #Name, #Marks)", con);
cmd.Parameters.AddWithValue("#rollNo", textBox1.Text);
cmd.Parameters.AddWithValue("#Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Marks", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Check your connection string. I usually write it as:
string Connection = #"Data Source=DELL\SQLEXPRESS;Initial Catalog = BSSE; Integrated Security = true";
If the roll number is supposed to be an integer, you need to parse
it.
int.Parse(textBox1.Text)
I suggest to use store procedures instead of sending blocks of SQL code from the c# Application, here is a reference to the SQL Store Procedures: https://msdn.microsoft.com/en-us/library/ms190782.aspx. You can reduce the possibility of SQL injection by adding parameters to your query instead of plain text, also you need to validate the input. You can create calls with parameters too. There are many ways to call a SQL database query from C#, Here is more information about Store Procedures that can give you a clue: http://csharp-station.com/Tutorial/AdoDotNet/Lesson07
Related
How to save a string in SQL Server as SqlDateType by using Visual Studio 2013? My string which I want to save is 1996-25-04. I am working with C#.
I have tried this as far
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass");
con.Open();
string sql = " insert into Staff_Management values( '" + TM_Add_BirthDate.Value.ToString() + "' ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
You should NEVER EVER concatenate together your SQL statements like this! This opens all doors to SQL injection attacks - and causes trouble with string and date values.
Try this code instead - using a parametrized query:
// define the query - and I'd recommend to always define the name of the columns you're inserting into
string query = "INSERT INTO dbo.Staff_Management(name-of-column-here) VALUES (#Birthdate);";
// define connection and command
// also: do **NOT** use the `sa` user for your production code!
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// add the parameter - and use the proper datatype - don't convert all dates to strings all the time!
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = TM_Add_Birthdate.Value;
// open connection, execute INSERT query, close connection - done
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
}
so I have a C# software which will save data to my database but every time I run my program and try to save data I get this message, please any help?
try
{
SqlConnection cnn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;
Integrated Security=True;User Instance=True");
cnn.Open();
SqlCommand cmd1 =
new SqlCommand("insert into user values('" +
textBox6.Text + "','" + textBox1.Text + "','" + textBox4.Text + "'," +
textBox3.Text + ",'" + textBox2.Text + "','" + textBox5.Text + "')",
cnn);
SqlDataReader dr1 = cmd1.ExecuteReader();
dr1.Close();
MessageBox.Show(" Record inserted ", " information inserted");
cnn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
Copy your database Bank_System.sdf in \bin\debug\ folder and change your connection string like this :
SqlConnection cnn = new SqlConnection("Data Source=" +#".\SQLEXPRESS;
AttachDbFilename=Bank_System.sdf;
Integrated Security=True;User Instance=True");
It should be worked, if an error occurs, try to execute your app from yourapp.exe located in \bin\debug\ folder
You are working with an SDF file. This file is for SQL Server Compact not for SQL Server Express (or full).
In this case the connection string should be simply:
#"Data Source=<fullpath_and file_to_your_sdf_file>;Persist Security Info=False;"
Notice that in C# you need to add the verbatim character in front of strings that contains special characters like the backslash
Working with Sql Server Compact requires to install the libraries required from the Microsoft Downloads and to use the proper classes. So, remove the SqlConnection and the SqlCommand classes and use the SqlCeConnection and SqlCeCommand (and so on for the other data client classes used in you app).
Of course the SqlCeConnection class can understand this different connection string syntax and allow to work with the SDF file
Said that, please revise your code that builds the sql command. Using string concatenation like your code does is a secure recipe for errors. From parsing errors (quotes inside your strings will break the syntax) to more serious error like Sql Injections
This could be an approach using a parameterized query....
try
{
string cmdText = "insert into user values(#p1, #p2, #p3,#p4,#p5,#p6)";
using(SqlCeConnection cnn = new SqlCeConnection(#"Data Source=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;Integrated Security=True"))
using(SqlCeCommand cmd1 = new SqlCeCommand(cmdText, cnn))
{
cnn.Open();
cmd.Parameters.AddWithValue("#p1", textBox6.Text);
cmd.Parameters.AddWithValue("#p2", textBox1.Text);
cmd.Parameters.AddWithValue("#p3", textBox4.Text);
cmd.Parameters.AddWithValue("#p4", textBox3.Text);
cmd.Parameters.AddWithValue("#p5", textBox2.Text);
cmd.Parameters.AddWithValue("#p6", textBox5.Text);
cmd1.ExecuteNonQuery();
MessageBox.Show(" Record inserted ", " information inserted");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, Sur-Name, Score,Avg) VALUES ('" + fName + "','" + sName + "','" + lblScore.Text + "','" + lblAvg.Text + "');");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#Sur-Name", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
finally
{
connection.Close();
}
The error I keep getting is a runtime saying
Incorrect syntax near '-'. Incorrect syntax near '-'.
I used the try catch just so page would load and my scores show but the label says this Incorrect syntax as well, I was wondering could anyone please help me with what I am doing wrong
Thanks.
I think Sur-Name breaks your query. Use it with square brackets like [Sur-Name]
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. I see you tried to use but you never declare your parameter names in your query.
Also DATA might be a reserved keyword on future versions of SQL Server. You might need to use with also like [DATA]
Consider to use using statement to dispose your SqlConnection and SqlCommand.
using(SqlConnection connection = new SqlConnection(ConnectionString))
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = #"INSERT INTO [Data] (Name, [Sur-Name], Score, Avg)
VALUES (#Name, #SurName, #Score, #Avg)";
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
}
You are trying to mix concatenated queries with parametrized. Always use parametrized queries, It will save you from SQL Injection.
SqlCommand cmd = new SqlCommand(#"INSERT INTO [Data] (Name, [Sur-Name], Score,Avg) VALUES (
#Name, #SurName, #Score, #Avg)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
Also consider enclosing your connection and command object in using statement.
As #Soner has mentioned in his answer, use Square brackets for Data and Sur-Name
I have a table and I want to delete all rows with a specific card serial . There are multiple rows with the same card serial .So I wrote this code but it seems that's not working:
try
{
using (SqlConnection con = new SqlConnection(WF_AbsPres.Properties.Settings.Default.DbConnectionString))
{
con.Open();
SqlCommand command2 = new SqlCommand("DELETE FORM DevInOut where Cardserial='" + textBox5.Text + "'", con);
command2.ExecuteNonQuery();
con.Close();
}
}
catch (SqlException ex)
{
}
how can assure all the rows will be deleted . Should I use procedure? How do I use procedure?
Change your FORM to FROM.
And please always use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
using (SqlConnection con = new SqlConnection(WF_AbsPres.Properties.Settings.Default.DbConnectionString))
{
con.Open();
SqlCommand command2 = new SqlCommand("DELETE FROM DevInOut where Cardserial=#Cardserial", con);
commdand2.Parameters.AddWithValue("#Cardserial", textBox5.Text);
command2.ExecuteNonQuery();
con.Close();
}
Read more from DELETE (Transact-SQL)
I think what I need is simple but I can't achieve it through asp.net because I am a total beginner.
What I need is to display a field from sql db table to my webpage like this example:
Account Information
Your Name is: <Retrieve it from db>
Your Email is: <Retrieve it from db>
How should I do that ?
I already have table members.
I need to do this with c# , I am using Visual Studio Web Express 2010
First step is add the SQL Client namespace:
using System.Data.SqlClient;
DB Connection
Then we create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
This is the last part of getting connected and is simply executed by the following (remember to make sure your connection has a connection string first):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand
An SqlCommand needs at least two things to operate. A command string, and a connection. There are two ways to specify the connection, both are illustrated below:
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
The connection string can also be specified both ways using the SqlCommand.CommandText property. Now lets look at our first SqlCommand. To keep it simple it will be a simple INSERT command.
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
// - or -
myCommand.CommandText = "INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)";
SqlDataReader
Not only do you need a data reader but you need a SqlCommand. The following code demonstrates how to set up and execute a simple reader:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}