C# MS SQL Update statement not updating database - c#

I have a local MS SQL Database, and I want to update one of it's bit field.
I have the following code:
static void UpgradeVevo(string nev)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=True Where Nev=" + nev, connection);
command.ExecuteNonQuery();
}
Console.WriteLine(nev+" mostmár törzsvendég");
}
Torzsvendeg is a bit datatype(I have tried to set its value to 1 too), and Nev is varchar.
The connectionstring should be fine, since I have tried Select in another method and it works fine. The above code throws no exceptions, but the table does not get updated.
I have tried to find an answer for quite some time, with no success :/. Thank you for your help in advance!

True should be in a single quote since it's a string literal like
UPDATE Vevok SET Torzsvendeg='True'
Well brother, you are messed up with quotes. Your query should look like
"UPDATE Vevok SET Torzsvendeg = 1 Where Nev = '" + nev + "'"
Again, use parametarized query and not this concatenated one to avoid SQL Injection

If the column is a boolean (bit in sql server) then you will have to write
Torzsvendeg=1
instead of
Torzsvendeg='True'
or
Torzsvendeg=True
Edit:
Please try this:
static void UpgradeVevo(string nev)
{
var connection = new SqlConnection(connectionString))
connection.Open(); // try doing this without a using
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=#enabled Where Nev=#nev", connection);
command.Parameters.AddWithValue(#"enabled", 1);
command.Parameters.AddWithValue(#"nev", "vevo123");
command.ExecuteNonQuery();
command.Parameters.Clear(); // always clear after executed
// close connection when you shut down your application
connection.Close();
connection.Dispose();
Console.WriteLine(nev+" mostmár törzsvendég");
}

Related

How to insert to service based database?

I read lots of topics and tried many solutions, but it is not working for me, to insert my data to the database.
public static void Feltoltes(string szo_var, string szotagolva_var)
{
string query = "";
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
{
command.Parameters.Clear();
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES ('#szo','#szotagolva')";
command.Parameters.AddWithValue("#szo", szo_var);
command.Parameters.AddWithValue("#szotagolva", szotagolva_var);
System.Windows.Forms.MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
}
conn.Close();
}
}
This is my code. My connection string is the right one. If I insert to the database manually, than I can make SELECTs etc. Only the Insert is not working properly. It don't get any exception, looks like everything works, but nothing changes.
Every thing looks OK except for the insert command text.
Try the following:
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES (#szo,#szotagolva)";
If you use single quates (') inside a SQL command text it will treat what is inside as a literal. And hence it cancels out your parameter designation #

Getting column information in SQL

I am somwhat new to SQL, so I am not sure I am going about this the right way.
I am trying to fetch data from my SQL Server database where I want to find out if checkedin is 1/0, but it needs to search on a specific user and sort after the newest date as well.
What I am trying to do is something like this:
string connectionString = ".....";
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand checkForInOrOut = new SqlCommand("SELECT CHECKEDIN from timereg ORDER BY TIME DESC LIMIT 1 WHERE UNILOGIN = '" + publiclasses.unilogin + "'", cnn);
So my question, am I doing this right? And how do I fetch the data collected, if everything was handled correctly it should return 1 or 0. Should I use some sort of SqlDataReader? I am doing this in C#/WPF
Thanks
using (SqlDataReader myReader = checkForInOrOut.ExecuteReader())
{
while (myReader.Read())
{
string value = myReader["COLUMN NAME"].ToString();
}
}
This is how you would read data from SQL, but i recommend you looking into Parameters.AddWithValue
There are some errors in your query. First WHERE goes before ORDER BY and LIMIT is an MySql keyword while you are using the Sql Server classes. So you should use TOP value instead.
int checkedIn = 0;
string cmdText = #"SELECT TOP 1 CHECKEDIN from timereg
WHERE UNILOGIN = #unilogin
ORDER BY TIME DESC";
string connectionString = ".....";
using(SqlConnection cnn = new SqlConnection(connectionString))
using(SqlCommand checkForInOrOut = new SqlCommand(cmdText, cnn))
{
cnn.Open();
checkForInOrOut.Parameters.Add("#unilogin", SqlDbType.NVarChar).Value = publiclasses.unilogin;
// You return just one row and one column,
// so the best method to use is ExecuteScalar
object result = checkForInOrOut.ExecuteScalar();
// ExecuteScalar returns null if there is no match for your where condition
if(result != null)
{
MessageBox.Show("Login OK");
// Now convert the result variable to the exact datatype
// expected for checkedin, here I suppose you want an integer
checkedIN = Convert.ToInt32(result);
.....
}
else
MessageBox.Show("Login Failed");
}
Note how I have replaced your string concatenation with a proper use of parameters to avoid parsing problems and sql injection hacks. Finally every disposable object (connection in particular) should go inside a using block

c# Update Command to Access Database

I am trying to update data in access table. However, i keep receiving a syntax error when i attempt to update. Below is the code ive compiled. Textbox37 is the one that requires updates.
string constr1;
constr1 = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Documents\\data.accdb;Jet OLEDB:Database";
string cmdstr = "Update Log(Notes,Status)Values(#a,#b) Where LogIncNum='" + LogInc + "'";
using (OleDbConnection con1 = new OleDbConnection(constr1))
{
using (OleDbCommand com = new OleDbCommand(cmdstr, con1))
{
com.CommandType = CommandType.Text;
com.Parameters.AddWithValue("#a", textBox37.Text);
com.Parameters.AddWithValue("#b", "Active");
con1.Open();
com.ExecuteNonQuery();
}
}
The correct syntax for an update statement is
UPDATE table SET field1=value1, field2=value2 WHERE field3=value3
You are using the wrong syntax hence the syntax error
As a side note, did you forget to use a parameter for the WHERE condition?
It is always correct to use a parameter for every value that you want to include in your query. Just remember to put it in the correct order because OleDb doesn't recognize the parameter by their name, but use a strictly positional order in the Parameters collection, so the first one goes assigned to the first parameter placeholder and so on.
easy way
using (var aq_pension = new System.Web.UI.WebControls.SqlDataSource())
{
aq_pension.ProviderName = "System.Data.OleDb";
aq_pension.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/stat_tresor/stat_tresor/stat_tresor/db/stat1.mdb";
aq_pension.UpdateCommand = "UPDATE tableaux1 SET nbre=0, montant_mois=0,total=0 WHERE code <>''";
aq_pension.Update();
}

sqltransaction insert a double record while insert data

I am using that sqltransaction for the insert multiple tables each data.
But I have problem that have the database have the two same data.
What should I do for solve that problem?
please help me? Thanx
SqlConnection baglanti = system.baglan();
SqlCommand Trislem1_Ekle = new SqlCommand("Insert tblTr (Ad,TipID,BolgeID,Yerler,Resim) values(#Ad,#TipID,#BolgeID,#Yerler,#Resim) SELECT SCOPE_IDENTITY()", baglanti);
SqlCommand Tr2_TrAciklama = new SqlCommand("Insert tblTrAciklamaDetay (TrID,TrProgram) values((SELECT IDENT_CURRENT('tblTr')),#TrProgram)", baglanti);
Trislem1_Ekle.Parameters.AddWithValue("#Ad", txtTrAd.Text);
Trislem1_Ekle.Parameters.AddWithValue("#TipID", dlTrTip.SelectedValue);
Trislem1_Ekle.Parameters.AddWithValue("#BolgeID", BolgeID.SelectedValue);
Trislem1_Ekle.Parameters.AddWithValue("#Yerler", Yerler.Text);
Trislem1_Ekle.Parameters.AddWithValue("#Resim", Resim.SelectedValue);
Tr2_TrAciklama.Parameters.AddWithValue("#TrProgram", TrProgram.Text);
SqlTransaction sqlTrans = baglanti.BeginTransaction();
Trislem1_Ekle.Transaction = sqlTrans;
Tr2_TrAciklama.Transaction = sqlTrans;
try
{
Trislem1_Ekle.ExecuteNonQuery();
Tr2_TrAciklama.ExecuteNonQuery();
string SonIDGelen = Trislem1_Ekle.ExecuteScalar().ToString();
sqlTrans.Commit();
}
catch (Exception hata)
{
Response.Write("İşleminiz yapılamadı, Oluşan Hatanın Detayı<br />" + hata);
sqlTrans.Rollback();
}
finally
{
baglanti.Close();
baglanti.Dispose();
Trislem1_Ekle.Dispose();
Tr2_TrAciklama.Dispose();
}
As far as I see, you executing your Trislem1_Ekle command twice.
One with
Trislem1_Ekle.ExecuteNonQuery();
and the other one with;
string SonIDGelen = Trislem1_Ekle.ExecuteScalar().ToString();
Deleting the first one seems enough. Both ExecuteNonQuery and ExecuteScalar executes your query, and ExecuteScalar returns first column of the first row additionally.
Instead of disposing your database connections and commands manually, use using statement instead.
using(SqlConnection conn = new SqlConnection(conString))
{
using(SqlCommand cmd = conn.CreateCommand())
{
// Create your commands
// Add your parameter values
// Execute your commands
}
}
And don't use AddWithValue method. It may generate some unexptected results. Use .Add() method and overloads instead.
Can we stop using AddWithValue() already?
try like this
I think you are executing ExecuteScalar() twice on Command Trislem1_Ekle
Trislem1_Ekle.ExecuteNonQuery();
Tr2_TrAciklama.ExecuteNonQuery();
string SonIDGelen = Trislem1_Ekle.ExecuteScalar().ToString();
Replace with this:
string SonIDGelen = Trislem1_Ekle.ExecuteScalar().ToString();
Tr2_TrAciklama.ExecuteNonQuery();

C# 'select count' sql command incorrectly returns zero rows from sql server

I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = sqlConnectionString;
cn.Open();
SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count: " + countStart.ToString());
}
Any suggestions on what could be causing it?
Here's how I'd write it:
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
cn.Open();
using (SqlCommand commandRowCount
= new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
{
commandRowCount.CommandType = CommandType.Text;
var countStart = (Int32)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count: " + countStart.ToString());
}
}
Set your CommandType to Text
command.CommandType = CommandType.Text
More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.
If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.
You can use this better query:
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'

Categories