Update only one column using ID in asp.net - c#

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();
}

Related

Data type mismatch in criteria expression - started only recently

I use Access database. This error wasn't occurring 30 minutes ago.
ERROR is:
Data type mismatch in criteria expression.
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid)
values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
My database columns are:
ID = AutoNumber
isin_adi = Short Text
isin_tanimi = Long Text
verildigi_tarih= Date/Time
teslim_tarihi=Date/Time
sorumlu_marka = Short Text
sorumlu_ajans=Short Text
personel_id=Number
revize=Short Text
is_durum=Short Text
Temsilci_isverenid=Number
I Solved the problem. I realized the rank of parameters was not true. i change my code like that:
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid) values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
after that i get error like this :
You cannot add or change a record because a related record is required in table 'Personel'.
And i remove the relationship from 2 tables. And now it works normally.
I think access database have some bugs ,and even if code is correct, errors may accuired.
So i will move my database to SQL from ACCESS i think. Thanks guys.

Invalid object name even if it exists

Here is my code:
InitializeComponent();
SqlConnection myConnection = new SqlConnection("data source = DESKTOP-77FA1JE;" +
"user id = DESKTOP-77FA1JE\\Chanloi" +
"initial catalog = TransactionProcessingSystem;" +
"integrated security = SSPI");
myConnection.Open();
SqlCommand myCommand = new SqlCommand("select * from UserAccounts", myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
BindingSource mySource = new BindingSource();
mySource.DataSource = myReader;
dataGridView1.DataSource = mySource;
myConnection.Close();
I get this error:
System.Data.SqlClient.SqlException: 'Invalid object name 'UserAccounts'.'
Very simple - You do not have a table called UserAccounts in your database.
Please try dbo.UserAccounts
In Such a Case What I Usually Do Is Run This Statment
select name from sys.tables
sys.Tables is a System View That Has info About The Existing Tables In Your Db , This Way You Can Check If The Table Already Exists or U Misspelled It's Name or Existed By Another Name , and Even But an if Condition To Execute Your Logic Only If This Table Exists
Also as Other Have Said it's A Good Practice To Put Column Names Between a [] Brackets , and Call It By Schema Name like dbo.MyTable
try this:
select * from dbo.[UserAccounts]
It's pretty straightforward. It's telling you that there is no UserAccounts table on your database. You can try dbo.UserAccounts, but if it fails, check your database first and also make sure you're connecting to right database.
Hope it helps!
The above exception says that the table UserAccounts does not exist in your database you are connected through your connection string
if the table is created do a local refresh cahce from Edit section and then intellisense and then refresh lcoal cache

Updating the sql server database in urdu(language) text

I am simply making a windows form in c# where I can insert, update and delete the data.
I want to insert data in URDU text. I am done with inserting data with following code :
SqlCommand cmd = new SqlCommand("insert into tblTeams values (#ID, #SchoolName, #TeamName)", con);
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text);
cmd.Parameters.AddWithValue("#SchoolName", txtBoxSName.Text);
cmd.Parameters.AddWithValue("#TeamName", txtBoxTName.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
But when trying to update data not getting any clue how to do it...
SqlDataAdapter sda = new SqlDataAdapter("update tblTeams set SchoolName='"+txtBoxSName.Text+"',TeamName='"+txtBoxTName.Text+"'where ID='"+txtBoxID.Text+"' ", con);
con.Open();
sda.SelectCommand.ExecuteNonQuery();
con.Close();
Above piece of code updates the database but not in URDU, in database only "?????" shows...
In SQL server all the insert, update and delete works but I want to do it in front end...
Form design is also attached...enter image description here
Thanks in advance!
Done with updation also and thanks for your support...
Here is the code:
SqlCommand cmd = new SqlCommand("update tblTeams set SchoolName=#SchoolName, TeamName=#TeamName where ID=#ID ", con);
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text);
cmd.Parameters.AddWithValue("#SchoolName", txtBoxSName.Text);
cmd.Parameters.AddWithValue("#TeamName", txtBoxTName.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
This is most likely happening because your columns don't support Unicode. You'll need to use nvarchar, or nchar in your columns.
Alternatively, your TextBox doesn't support unicode text. Try a different font, like Arial.
Don't use the update code without Parameters. It's vulnerable to SQL injection attacks. Instead, use parameters in both, like you did in the first.
Finally, you can prefix the insert values with N'urdutexthere', like this:
SqlCommand cmd = new SqlCommand("UPDATE tblTeams SET SchoolName=N'#SchoolName',TeamName=N'#TeamName' WHERE ID='#ID'", con);
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text);
cmd.Parameters.AddWithValue("#SchoolName", txtBoxSName.Text);
cmd.Parameters.AddWithValue("#TeamName", txtBoxTName.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

c# cant insert row but can select

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)

C# : SQL Server query issue

I create a table in SQL Server Management Studio with this code:
CREATE TABLE contact(
ID INT IDENTITY NOT NULL,
FIRSTNAME VARCHAR(100),
LASTNAME VARCHAR(100)
)
and in C# I used this code:
SqlConnection sc = new SqlConnection("Data Source=.\\SQLSERVER; Initial Catalog=BOSS; Integrated Security=TRUE");
SqlDataAdapter sd = new SqlDataAdapter();
sd.InsertCommand = new SqlCommand("INSERT INTO contact VALUES(#ID, #FIRSTNAME, #LASTNAME)");
sd.InsertCommand.Parameters.Add("#ID", SqlDbType.Int).Value = textBox1.Text;
sd.InsertCommand.Parameters.Add("#FIRSTNAME", SqlDbType.VarChar).Value = textBox2.Text;
sd.InsertCommand.Parameters.Add("#LASTNAME", SqlDbType.VarChar).Value = textBox3.Text;
sc.Open();
sd.InsertCommand.ExecuteNonQuery();
sc.Close();
but when I add the values to the database I get the error:
"ExecuteNonQuery: Connection property has not been initialized"
and I fixed it by adding sc to my first insertcommand, but when I run the program I got another error :
An explicit value for the identity column in table 'contact' can only
be specified when a column list is used and IDENTITY_INSERT is ON.
Do it this way:
using(SqlConnection sc = new SqlConnection("Data Source=.\\SQLSERVER; Initial Catalog=BOSS; Integrated Security=TRUE"))
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "INSERT INTO contact (FirstName, LastName) VALUES(#FIRSTNAME , #LASTNAME");
command.CommandType = CommandType.Text;
command.Connection = sc;
command.Parameters.AddWithValue("#FIRSTNAME", textBox2.Text);
command.Parameters.AddWithValue("#LASTNAME", textBox3.Text);
sc.Open();
command.ExecuteNonQuery();
}
}
Important things to note:
1) Set your table up to have the Id column as an identity column and set autoincrement to true. This will automatically generate a numeric id when you insert
2) You are trying to insert into an identity column - you can't actually do this unless you enable identity inserts. I wouldn't bother - just use an autoincrement column and let the database control the id generation step.
You can generate your table this way:
CREATE TABLE Contact
(
Id int PRIMARY KEY IDENTITY,
FirstName varchar(100),
LastName varchar(100)
)
to get an autoincrementing primary key.
3) You don't need the SqlDataAdapter.
You need to pass the connection you intend to use to the SqlCommand
InsertCommand = new SqlCommand("INSERT INTO contact VALUES(#ID , #FIRSTNAME , #LASTNAME)", sc);
You need to dispose of your Connection and command as well. The standard pattern for doing this is:
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLSERVER; Initial Catalog=BOSS; Integrated Security=TRUE")){
conn.Open();
using (SqlCommand command = new SqlCommand(sqlString, conn)){
//stuff...
command.ExecuteNonQuery();
}
}
There's no relation between SqlConnection and SqlDataAdapter.
In fact, you don't need SqlDataAdapter. You only need SqlConnection and SqlCommand, for which you must use the constructor overload that accepts a connection as well.
Since ID is an INT IDENTITY field, you shouldn't (and can't) insert values into it. But if you use your "generic" INSERT statement without explicitly specifying which columns to insert values into, your INSERT statement will attempt to insert data into all columns - including ID, which you cannot insert anything into.
The solution (which I recommend for use always) is to explicitly define which columns to insert values into:
INSERT INTO dbo.contact(FirstName, LastName) VALUES(#FIRSTNAME, #LASTNAME)
This also works if you need to change your table and add another column - your original statement will fail, since the table suddenly now would have four columns, but your statement would only provide three values. If you explicitly define which columns you want to provide values for, your statement is more robust and works better.
So your complete code should look like this:
using(SqlConnection sc = new SqlConnection("Data Source=.\\SQLSERVER; Initial Catalog=BOSS; Integrated Security=TRUE"))
using(SqlCommand cmdInsert = new SqlCommand("INSERT INTO dbo.Contact(FirstName, LastName) VALUES(#FIRSTNAME, #LASTNAME)", sc))
{
cmdInsert.Parameters.Add("#FIRSTNAME", SqlDbType.VarChar, 100).Value = textBox2.Text;
cmdInsert.Parameters.Add("#LASTNAME", SqlDbType.VarChar, 100).Value = textBox3.Text;
sc.Open();
cmdInsert.ExecuteNonQuery();
sc.Close();
}
You need sd.InsertCommand = new SqlCommand("INSERT INTO contact VALUES(#ID , #FIRSTNAME , #LASTNAME)", sc);
You can do either ways:
a. Set you connection object to the adapter's insertcommand connection:
sd.InsertCommand.Connection = sc;
Or
b. Pass your connection object while initializing insert command as below:
sd.InsertCommand =
new SqlCommand("INSERT INTO contact VALUES(#ID, #FIRSTNAME, #LASTNAME)", sc);

Categories