Hello guys I have got this code:
SqlCommand scom = new SqlCommand(
"INSERT INTO klient(name,surname)
values(#kname,#ksurname)",
conn);
scom.Parameters.AddWithValue("#kname", kname.Text);
scom.Parameters.AddWithValue("#ksurname", ksurname.Text);
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM klient", spojeni);
SDA.Fill(dt);
conn.Close();
It should insert data from textboxes: kname, ksurname, but it closes the form without showing them in MS SQL table klient
Missing the ExecuteNonQuery call
SqlCommand prikaz = new SqlCommand("INSERT INTO klient(name,surname) values(#kname,#ksurname)", spojeni);
prikaz.Parameters.AddWithValue("#kname", kname.Text);
prikaz.Parameters.AddWithValue("#ksurname", ksurname.Text);
spojeni.Open();
prikaz.ExecuteNonQuery();
......
A command should be executed to update the database...
You haven't executed the command.
prikaz.ExecuteNonQuery();
The above stated problem is due to the missing executenonquery() statement, add this statement in your code
spojeni.Open();
prikaz.ExecuteNonQuery();
Related
I want to insert new record into the DataTable with DataAdapter.
There are 2 columns in Person table. FirstName and LastName.
I have a code like below.
SqlConnection connection;
DataSet dsPerson;
SqlDataAdapter adapter;
string connectionString = Properties.Resources.ConnectionString;
connection = new SqlConnection(connectionString);
dsPerson = new DataSet("PersonDataSet");
adapter = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Person", connection);
adapter.SelectCommand = selectCommand;
adapter.Fill(dsPerson, "Person");
string insertQuery = "INSERT INTO Person(FirstName, LastName) VALUES (#FirstName, #LastName)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add(new SqlParameter("#FirstName", SqlDbType.NVarChar));
insertCommand.Parameters["#FirstName"].SourceVersion = DataRowVersion.Current;
insertCommand.Parameters["#FirstName"].SourceColumn = "FirstName";
insertCommand.Parameters.Add(new SqlParameter("#LastName", SqlDbType.NVarChar));
insertCommand.Parameters["#LastName"].SourceVersion = DataRowVersion.Current;
insertCommand.Parameters["#LastName"].SourceColumn = "LastName";
adapter.InsertCommand = insertCommand;
But when I try to insert new Record into DataSet it appears in the DataSet. But it does not do insert new record into DataBase.
The Code for Insert is below.
connection.Open();
DataRow newRow = dsPerson.Tables["Person"].NewRow();
newRow["FirstName"] = "Joseph";
newRow["LastName"] = "Sword";
dsPerson.Tables["Person"].Rows.Add(newRow);
dsPerson.Tables["Person"].AcceptChanges();
dsPerson.AcceptChanges();
adapter.Update(dsPerson, "Person");
connection.Close();
I even try to trace queries sent to sql server With Express Profiler. And i saw that it does not send insert command to the database.
So what is the problem? How to solve it?
Thank you.
You should not call AcceptChanges methods of dataset and DataTable because DataAdapter.Update method affects only changed/added/deleted rows from datatable.
But after calling AcceptChanges all your DataRows will have Unchanged state.
See MSDN for reference about DataAdapter:
When an application calls the Update method, the DataAdapter examines
the RowState property, and executes the required INSERT, UPDATE, or
DELETE statements iteratively for each row, based on the order of the
indexes configured in the DataSet.
I have created a view called view_SelectAll_Student in SQL Server which retrieves all columns from single table name
And I have a function that returns dataset or datatable using dataadapter somehow I get this error:
The request for procedure 'view_SellectAll_Student' failed because 'view_SellectAll_Student' is a view object.
Code:
public DataTable ViewStudentAll()
{
cons.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("view_SellectAll_Student", cons);
cmd.Connection = cons;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt;
}
Views still need to be queried. What you have here is just the view name..
So change this:
cmd = new SqlCommand("view_SellectAll_Student",cons);
to this:
cmd = new SqlCommand("SELECT put, columns, here FROM view_SellectAll_Student",cons);
Make sure you put the columns of the view there (or an asterisk.. if you're that way inclined).
Write it like this. If its a view you should SELECT it otherwise you wont get it.
cmd = new SqlCommand("SELECT * FROM view_SellectAll_Student",cons);
cmd.Connection = cons;
//cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt;
TIP: While using a DataAdapter there is no need of con.Open() or con.Close() statement. DataAdapter itself will open and close it.
The SqlDataAdapter accepts as first argument an SqlCommand which can
be a Select statement or stored procedure.
In this case you can replace "view_SellectAll_Student" with
"Select * from view_SellectAll_Student"
cons.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("select * view_SellectAll_Student",cons);
cmd.Connection = cons;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt;
How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
my problem is that , i made a child form for searching , but i have problem in sql query and parameters , my code is
SqlConnection sc = new SqlConnection(
"Data Source=MOHAMMED-PC;Initial Catalog=salessystem;Integrated Security=True");
SqlCommand command = new SqlCommand(
"Select * from customers WHERE (docno = #doc) OR (NAME LIKE #name ) OR (salepoint = #salepoint)", sc);
DataTable dt = new DataTable();
command.Parameters.AddWithValue("#doc", doctxt.Text);
command.Parameters.Addwithvalue("#name", nametxt.Text);
command.Parameters.AddWithValue("#salepoint", salepointtxt.Text);
SqlDataAdapter sda = new SqlDataAdapter(command, sc);
sda.Fill(dt);
dataGridView1.DataSource = dt;
i have error in sql adapter command and in where clause command , any help ??
Three things:
You have a typo on this line
command.Parameters.Addwithvalue("#name", nametxt.Text);
The method is AddWithValue (note the case difference)
The constructor of SqlDataAdapter takes the command but no connection then since the command already contains the connection, so this is correct:
SqlDataAdapter sda = new SqlDataAdapter(command);
Probably the most important last:
If you use LIKE you need to use the wild-cards %:
command.Parameters.AddWithValue("#name", string.Format("%{0}%",nametxt.Text);
I'm not sure, but I think I may have taken a wrong path here. I am trying to update my customer table on my SQL Server. I Connected with a SQLDatareader and then loaded that into my Datatable. I have made all the changes I wanted and now I can't figure out how to get the changes back up. I thought that the "myDataTable.AcceptChanges();" would trigger that to happen but it doesn't.
SqlConnection myConnection = new SqlConnection();
SqlCommand myCommand;
DataTable myDataTable;
SqlDataReader myReader;
myCommand = new SqlCommand();
myCommand.CommandText = " SELECT * FROM customer";
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
myDataTable = new DataTable();
myDataTable.Load(myReader);
// Make Data changes here
myDataTable.AcceptChanges();
MyDataTable.Dispose();
MyCommand.Dispose();
MyConnection.Dispose();
You can use a TableAdapter to commit your changes back to the database. Check out this link for details.
TableAdapter.Update()
In such case you need to use a DataAdapter which has an Update property that takes your Update Query Command.
Even you can use Command Builder and then get the UpdateCommand from CommandBuilder.
Sample Code from MSDN
SqlDataAdapter catDA = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories", nwindConn);
catDA.UpdateCommand = new SqlCommand("UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID" , nwindConn);
catDA.UpdateCommand.Parameters.Add("#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter workParm = catDA.UpdateCommand.Parameters.Add("#CategoryID", SqlDbType.Int);
workParm.SourceColumn = "CategoryID";
workParm.SourceVersion = DataRowVersion.Original;
DataSet catDS = new DataSet();
catDA.Fill(catDS, "Categories");
DataRow cRow = catDS.Tables["Categories"].Rows[0];
cRow["CategoryName"] = "New Category";
catDA.Update(catDS);
MSDN Link