|
hi
can anybody tell me how to save data to database using visual studio 2008(c#).
in sqlserver2005.
i had created the design in web application form.
please send me the code of save button.(c#)
|
|
|
|
|
shubham salwan wrote: please send me the code of save button.(c#)
We're not in the business of providing "free code". You are the programmer, your salary, you learn to write code to earn that.
If you're stuck, you can get hints and tips here. In this case, saving data to a database is usually done using an UPDATE statement in Sql. If that doesn't make any sense, then you'd best begin by finding a good book and reading up on the topic.
Bastard Programmer from Hell
if you can't read my code, try converting it here[^]
|
|
|
|
|
protected void btnSave_Click(object sender, EventArgs e)
{
string connString = "Data Source=ServerName;Initial Catalog=DbName;Integrated Security=True"; SqlConnection conn = new SqlConnection(connString);
conn.Open();
String sql = "INSERT INTO CustomerInfo(FirstName, LastName, Address, Order, Quantity) values ('Sai', 'Prasad', 'Hyderabad', 1, 100)";
SqlCommand cmd = new SqlCommand(sql,conn);
cmd.ExecuteNonQuery();
conn.Close();
}
|
|
|
|
|
Sure that works, but it is very very bad on several levels and showing it to a newbie will only create yet another newbie who doesn't write data access code properly and then has to come back and ask why things aren't working as expected.
0) You should put the actual DB access code in a Data Access Layer, then call the API of the DAL from the UI layer.
1) You should always use a parameterized query.
2) You should handle Exceptions.
|
|
|
|
|
the thing is that i use to make web sites in visual studio..
i m trying window application form.. thatz y facing problem
|
|
|
|
|
That shouldn't matter, a proper Data Access Layer can be called from many front-ends.
|
|
|
|
|
error occured
that
the type or namespace name sqlcommand could not be found
|
|
|
|
|
include below namespace in your projcet:
using System.Data.SqlClient;
|
|
|
|
|
Have a read of this using ADO.NET[^]
there are some simple tutorials in the article
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|
If the data you want to save is in a grid which is data-bound to a database table or view, or you're using EF or similar. you can just ask it to persist itself. Otherwise, you're going to have to construct a SQL query to store the data that you want. SQL Server 2005 doesn't have an equivalent of 'insert ... on duplicate key update' so doing a single query can be impossible.
Make sure you use a parameterised query, and handle failures to write gracefully.
|
|
|
|