c# developers, can you say what wrong in that simple code?
public SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WpfApplication.Properties.Settings.BRDSConnectionString"].ToString());
public DataTable dt;
private void FillDataGrid()
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WpfApplication.Properties.Settings.BRDSConnectionString"].ToString());
SqlCommand comm = new SqlCommand("select * from B_RDS_DIST",con);
SqlDataAdapter da = new SqlDataAdapter(comm);
dt = new DataTable();
da.Fill(dt);
CBDist.ItemsSource = dt.DefaultView;
CBDist.DisplayMemberPath = "NAM";
CBDist.SelectedValuePath = "KEY";
try
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO B_RDS_DIST (NAM) VALUES (#NAM)", con);
cmd.Parameters.Add("#NAM", SqlDbType.VarChar, 255).Value="sadName";
da.InsertCommand = cmd;
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I can select, but can't insert. No exeptions here.
Table has only two columns KEY (PK,AI) and NAM (varchar 255).
May be I need to do something with connection to allow insert, or I missed something?
Thanks.
added
almost forgot, i use mdf file, so connectionString looks like:
"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BRDS.mdf;Integrated Security=True"
ANSWER - copy-paste pleas, i have no rputation.
Oh god, that was so dramatical old problem with generated Connection string!
Old connection string:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BRDS.mdf;Integrated Security=True"
New connection string:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Im awsome\Documents\Visual Studio 2013\Projects\WpfApplication\WpfApplication\BRDS.mdf;Integrated Security=True"
Insert/Delete/Update works well.
I have only two "simple for you" questions now:
1) How can i use dataTable to update simple table in database. Do i need create data table with one column "NAM"?
2) Why is so hard to detect this damn simple problem with connection string!? :D
If this is how you want to do this....
Edited:
SqlDataAdapter lcDataAdapter = new SqlDataAdapter()
lcDataAdapter.InsertCommand = new SqlCommand("INSERT INTO B_RDS_DIST (NAM) VALUES (#NAM)", con);
lcDataAdapter.InsertCommand.Parameters.Add("#NAM", SqlDbType.VarChar, 255).Value="sadName";
lcDataAdapter.InsertCommand.ExecuteNonQuery();
Note: I would not use the InsertCommand method on the data adapter for inserting records, but this is a case of developer preference. The above should work for you though as-is.
That is not how you use DataAdapters, you need to call da.Update(dt) to invoke any Insert, Update, or Delete queries that need to be performed on the DataTable to reflect any changes you made to the original DataTable.
Either totally seperate out your insert command from the data adapter or add the row to the data table you populated from Fill(dt) and don't use separate connecting strings (it would actually be better to not write your own insert at all and use SqlCommandBuilder and just do da.InsertCommand = cmdBuilder.GetInsertCommand(); and it will automaticly build the insert based off of the Select you passed in to the DataAdapter)
Related
I have two CheckedListBoxes, Standard Codes and Standard Details. Upon initialization, Standard Codes is populated from a query to the database.
InitializeComponent();
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Project;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter
("SELECT [StandardCode] FROM [dbo].[StandardCodesAndDetails]", conn);
adapter.Fill(ds);
this.lstBoxStandardCodes.DataSource = ds.Tables[0];
this.lstBoxStandardCodes.DisplayMember = "StandardCode";
conn.Close();
From this CheckedListBox, the user is able to select multiple Standard Code values. As these values are checked or unchecked, I want to run a query that will populate the Standard Details CheckedListBox with the related Standard Details from the database, with some Standard Codes having more than one Standard Detail. This is the part I'm not sure how to write. I'm not sure how to include checked CheckedListBox values in a SQL statement like this.
Any help at all would be appreciated. Thank you.
You have to create your sql statement dynamically instead of hard coding it.For example I will write a method which provide a sql statement based on user input like this.
public string CreateSQL(string userName,string password)
{
string sql="SELECT * FROM Table WHERE";
if(!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
sql+=" UserName='"+userName+"' AND Password='"+password+"'";
}
else if(!string.IsNullOrWhiteSpace(userName))
{
sql+=" UserName='"+userName+"'";
}
else if(!string.IsNullOrWhiteSpace(password))
{
sql+=" Password='"+password+"'";
}
else
{
sql=null;
}
return sql;
}
Through designer I have created a typed data set and included stored procedures for insert / update / delete. The problem is now, how to call those stored procedures? How to actually change data in database this way? And how to receive answer from db (number of rows changed)?
try this for get data from database.
DataSet ds = new DataSet("dstblName");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("spselect", conn);
sqlComm.Parameters.AddWithValue("#parameter1", parameter1value);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
Similarly you need to call "spdelte" etc.
I found out that far easiest way is through designer - create table adapter and simply set it to call stored procedure. No extra typing needed, arguments are also added to procedure call.
I want to update only one column in my table by ID .
I don't have any error but this don't work, it won't update. I have ID column and 7 more columns.
SqlCommand cmd1 = new SqlCommand("update table set amount=#kol where ID=#id" , con);
cmd1.Parameters.AddWithValue("#id", textbox1.Text);
cmd1.Parameters.AddWithValue("#kol", textbox2.Text );
Is your table named "table" or is that just for the example here?
Because otherwise you properbly need to change "table" to whatever table your're trying to update. or surround it with [] if it is actually called "table"
Can you please check that you have commited your work , if there is no exception then that will be the reason
and if not put setautocommit(true) - java version
you can find it for c#
please check whether table name is correct and the table which you are verifying is correct
please give some other table name than table for good practice
As long as you have con.Open and ExecuteNonQuery and have the username/password and connectionstring right your code will work.
This will work after you change the connectionstring, if not the problem is sql server.
private void UpdateTable()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=YourDataBase;Persist Security Info=True;User ID=username;Password=pass");
SqlCommand cmd1 = new SqlCommand("update YourTable set amount=#kol where ID=#id", con);
cmd1.Parameters.AddWithValue("#id", textBox1.Text);
cmd1.Parameters.AddWithValue("#kol", textBox2.Text);
con.Open();
cmd1.ExecuteNonQuery();
}
Could somebody take a quick peek at my ado.net code? I am trying to update the row from a dataset, but it just isn't working. I am missing some elemental piece of the code, and it is just eluding me. I have verified that the DataRow actually has the correct data in it, so the row itself is accurate.
Many thanks in advance.
try
{
//basic ado.net objects
SqlDataAdapter dbAdapter = null;
DataSet returnDS2 = new DataSet();
//a new sql connection
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Server=myserver.mydomain.com;"
+ "Database=mydatabase;"
+ "User ID=myuserid;"
+ "Password=mypassword;"
+ "Trusted_Connection=True;";
//the sqlQuery
string sqlQuery = "select * from AVLUpdateMessages WHERE ID = 21";
//another ado.net object for the command
SqlCommand cmd = new SqlCommand();
cmd.Connection = myConn;
cmd.CommandText = sqlQuery;
//open the connection, execute the SQL statement and then close the connection.
myConn.Open();
//instantiate and fill the sqldataadapter
dbAdapter = new SqlDataAdapter(cmd);
dbAdapter.Fill(returnDS2, #"AVLUpdateMessages");
//loop through all of the rows; I have verified that the rows are correct and returns the correct data from the db
for (int i = 0; i <= returnDS2.Tables[0].Rows.Count - 1; i++)
{
DataRow row = returnDS2.Tables[0].Rows[i];
row.BeginEdit();
row["UpdatedText"] = #"This is a test...";
row.EndEdit();
}
//let's accept the changes
dbAdapter.Update(returnDS2, "AVLUpdateMessages");
returnDS2.AcceptChanges();
myConn.Close();
}
I think you need an update query in your data adapter. I know, this sucks... Alternatively you can use CommandBuilder class to automatically generate queries for CRUD operations.
example at: http://www.programmersheaven.com/2/FAQ-ADONET-CommandBuilder-Prepare-Dataset
You might be able to use SqlCommandBuilder to help out. After the Fill call, add the following statement. That will associate a command builder with the data adapter and (if there is a primary key available) it should generate the update statement for you. Note that there is some expense behind the command builder. It may not be much relative to everything else, but it does involve looking at schema information (to get primary key information, field names, field types, etc.) for the table and generating INSERT, DELETE, and UPDATE statements involving all fields in the table.
SqlCommandBuilder cb = new SqlCommandBuilder(dbAdapter);
Wait, why not something like
update AVLUpdateMessages set UpdatedText = 'This is a test...' where id = 21
If you're picking through all the rows of a table to update one at a time, you're probably doing it wrong. SQL is your friend.
I have a data adapter. When I check the function at runtime I see the changes, but nothing happens in the database. How do I debug this? What went wrong?
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT * FROM tasks";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
connection.Open();
adapter.Fill(ds.Tables["Tasks"]);
adapter.Update(ds);
return ds;
Nothing is happening in the database because you're running a SELECT query. What are you expecting to happen?
Well unless you snipped a lot of code, you are not changing anything in the dataset per se.
What are you trying to achieve?
Here, you are selecting some data, filling the dataset with it, then putting back the unchanged dataset in the DB.
You should first change something in the dataset itself before calling adapter.Update(ds)
Cheers,
Florian
You are selecting data via the SelectCommand. If you want to update data, you need to run the UpdateCommand.
I assume you didn't post the full source code, as it looks as though you're not modifying the dataset. However, I just tweaked your code a bit (see my comments).
Hopefully this will help...
string queryString = "SELECT * FROM tasks";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
connection.Open(); // open connection first
SqlCommand cmd = new SqlCommand(queryString, connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); // use the cmd above when instantiating the adapter
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Fill(ds.Tables["Tasks"]);
// Modify your dataset here.
// Don't call AcceptChanges() as this will prevent the update from working.
adapter.Update(ds);
connection.Close(); // Close connection before ending the function
return ds;
This should allow OleDbCommandBuilder to do its thing by automatically scripting the database updates.
As far as I can see you've not actually changed any of the contents of the tasks table. When you call adapter.Fill you are populated the empty dataset with the records from the database. You are then calling adapter.Update without changing any records within the dataset. The update command only performs changes when the dataset > datatable > datarows are edited and marked as dirty.
you are only specifying the select command. you also need to specify the insert command... i.e:
DataAdapter.InsertCommand = new OleDbCommand....