I've calculated my 'ERna', and now I want to update it to my SQL Server database. I've made the statement, but I don't quite get how I get it to update in my database from C#.
Any ideas?
decimal ERna = ERnu - bprijs;
lbEigenRisico.Content = ERna;
string updateQuery = "UPDATE Verzekering SET eigen_risico = #ERna";
SqlCommand command = new SqlCommand(updateQuery, dbconn.Connection);
command.Parameters.AddWithValue("#ERna", ERna);
You just need to open the connection and call command.ExecuteNonQuery()
Related
I'm pretty much new to Vertica and its flex tables concept. Need to insert data into the flex table with help of odbcParameter like that
string query = "INSERT INTO flexTable SELECT MapJSONExtractor(#flexDataToInsert) as event"
var connection = GetConnection(); // returns OdbcConnection
var command = GetCommand(connection, queryString.ToString()); // returns OdbcCommand
OdbcParameter param = command.Parameters.Add("#flexDataToInsert", OdbcType.NText, 2048);
param.Value = data; // long json to insert
await command.ExecuteNonQueryAsync()
but get the exception "OdbcException: ERROR [42703] ERROR 2624: Column "flexDataToInsert" does not exist". After struggling for hours still can't realize what's wrong with it
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");
}
I'm writing a simple desktop application in which I'm using a local SQL database (SQL Server CE). Here is the problematic section:
SqlCeConnection conn = new SqlCeConnection("Data Source=|DataDirectory|\\App_Data\\Rosters.sdf");
System.Data.SqlServerCe.SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;
cmd.CommandText = String.Format("Insert into Teams (LeagueID, TeamName, Color) values ({0},'{1}','{2}');SELECT ##IDENTITY;", leagueID, txtTeamName.Text.Replace("'", "''"), txtColor.Text.Replace("'", "''"));
conn.Open();
int teamID = (int)cmd.ExecuteScalar();
conn.Close();
The problem is that I'm getting an exception when I call cmd.ExecuteScalar.
The exception message reads,
{"There was an error parsing the query. [ Token line number =
1,Token line offset = 97,Token in error = SELECT ]"}
I have run the exact same command in the exact same database through a direct query, and it runs fine - which makes me think the problem is not with SQL Server CE.
Any help would be greatly appreciated.
SQL Server Compact only supports a single statement per command, so first run the insert statement with executenonquery, then get the identity with executescalar, and remember not to close the connection in between
I need a sample C# (console application) code witch connects to an SQL Server Express database
and inserts a few variables into a table "laptops"
SQL Server Express is # localhost
user name is database
and password is testdatabase
What is the proper way to do that ?
Basic ADO.NET 101:
set up a connection
set up a command to do something
execute that command
Step 1: setting up a connection
You need to know the connection string to your database. Check out http://www.connectionstrings.com for a ton of examples.
In your case, you say it's a local SQL Server Express instance - but unfortunately, you didn't mention what your database is called..... your connection string will be something like:
server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase
Step 2: setting up a command
You can have various commands - to select data, to delete that, or to insert data. Whatever you do - I would recommend to always use parametrized queries to avoid SQL injection.
So your code here would look something like:
string connectionString = "server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase";
string insertStmt = "INSERT INTO dbo.Laptops(Name, Model, ScreenSize) " +
"VALUES(#Name, #Model, #Screensize)";
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
// set up the command's parameters
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = "ASUS SX30";
cmd.Parameters.Add("#Model", SqlDbType.VarChar, 50).Value = "Ultralight";
cmd.Parameters.Add("#Screensize", SqlDbType.Int).Value = 15;
// open connection, execute command, close connection
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
}
I'm using the MySql Connector .net, and I need to get the insert id generated by the last query. Now, I assume the return value of MySqlHelper.ExecuteNonQuery should be the last insert id, but it just returns 1.
The code I'm using is:
int insertID = MySqlHelper.ExecuteNonQuery(Global.ConnectionString,
"INSERT INTO test SET var = #var", paramArray);
However insertID is always 1. I tried creating a MySql connection and opening/closing manually which resulted in the same behaviour
Just use LastInsertedId field
MySqlCommand dbcmd = _conn.CreateCommand();
dbcmd.CommandText = sqlCommandString;
dbcmd.ExecuteNonQuery();
long imageId = dbcmd.LastInsertedId;
1 is the no of records effected by the query here only one row is inserted so 1 returns
for getting id of the inserted row you must use scope_identity() in sqlserver and LAST_INSERT_ID() in MySql
Try to use this query to get last inserted id -
SELECT LAST_INSERT_ID();
Then, run DbCommand.ExecuteReader method to get IDataReader -
command.CommandText = "SELECT LAST_INSERT_ID()";
IDataReader reader = command.ExecuteReader();
...and get information from the reader -
if (reader != null && reader.Read())
long id = reader.GetInt64(0);
...do not forget to close the reader;-)
I had the same problem, and after some testing, I found out that the problem seem to be the connection method; you are using a connection string.
This is of course to make use of the automatic connection pool reuse, but in this case it gave me trouble.
The final solution for me is to create a new connection, execute the insert query, and then execute the last_insert_id(). On the same connection.
Without using the same connection, last_insert_id() might return anything, I don't know why, but guess it looses track of things as it can be different connections.
Example:
MySqlConnection connection = new MySqlConnection(ConnectionString);
connection.Open();
int res = MySqlHelper.ExecuteNonQuery(
connection,
"INSERT INTO games (col1,col2) VALUES (1,2);");
object ores = MySqlHelper.ExecuteScalar(
connection,
"SELECT LAST_INSERT_ID();");
if (ores != null)
{
// Odd, I got ulong here.
ulong qkwl = (ulong)ores;
int Id = (int)qkwl;
}
I hope this helps someone!
I know this is an old post, but I have been facing the same issue as Snorvarg. Using MySqlHelper, and using a connection string instead of a Connection object (to allow MySqlHelper to use connection pooling), SELECT LAST_INSERT_ID() would often give me the ID of the previous query that was executed, or other times it would return zero. I would then have to call SELECT LAST_INSERT_ID() a second time to get the correct ID.
My solution was to encapsulate everything between the query that's being executed, and the calling of SELECT LAST_INSERT_ID() in a TransactionScope. This forces MySqlHelper to stick to one connection instead of opening two separate connections.
So:
string sql = "INSERT INTO games (col1,col2) VALUES (1,2);");
string connectionString = "some connection string";
using (TransactionScope scope = new TransactionScope)
{
int rowsAffected = MySqlHelper.ExecuteNonQuery(connectionString, sql);
object id = MySqlHelper.ExecuteScalar(connectionString, "SELECT LAST_INSERT_ID();");
scope.Complete();
}
try below working solution in repository .
string query = $"INSERT INTO `users`(`lastname`, `firstname`, `email`, `createdate`, `isdeleted`) " +
$"VALUES ('{userEntity.LastName}','{userEntity.FirstName}','{userEntity.Email}','{userEntity.CreateDate}',{userEntity.IsDeleted});" +
$"SELECT LAST_INSERT_ID();";
var res= _db.ExecuteScalar(query);
return (int)(UInt64)res;