SQL How to replace a value - c#

I'm using a Database I was able to get all the data from the database and save it in a List<>. I made changes in the List<> using a DataGrid and now I want to replace each Database value for the List<> values WHERE the List.ID == Database ID. I use Dapper (In case it matters);
public void SetData(List<DatabaseInfoModel> database)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection("Server=.\\SQLEXPRESS; Database=XXXX; User Id=XXXX; Password=password;"))
{
foreach(DatabaseInfoModel item in database)
{
connection.Execute($"UPDATE DataTable " +
$"SET Name = {item.Name}, " +
$" Description = {item.Description}, " +
$" Record = {item.Record} " +
$" WHERE ID = {item.ID}");
}
}
}

you can pass a model, ex
.Execute("update mydogs set age=#Age where id=#Id",dog);
"dog" is your model

UPDATE DataTable
SET
Name = REPLACE(Name, item.Name, 'Replacement Value')
.
.
WHERE ID = {item.ID}
Is this what you are looking for ?
In case you are looking for the syntax, here is more information:
https://learn.microsoft.com/en-us/sql/t-sql/functions/replace-transact-sql?view=sql-server-ver15

Related

search for parameters with square brackets in an access query

I try to identify in C# ,a DB Access with thousands of queries, only the queries with fictitious parameters,
(eg. Select id, Nation, Name from someTable where Nation = [Give a Nation]).
I tried with GetOleDbSchemaTable but with no luck.
I also tried to use MSysQueries and MSysObjects from Access and then retrieve the info in C # but with no luck.
How can you help me?
You have to ref the interop - this one:
using System.Data.OleDb
Imports Microsoft.Office.Interop.Access.Dao
public void ShowParms()
{
var strPath = #"C:\Users\AlbertKallal\source\repos\DesktopFun\test44.accdb";
Database db;
DBEngine dbACE = new DBEngine();
db = dbACE.OpenDatabase(strPath);
QueryDef query;
Parameter qParm;
foreach (var query in db.QueryDefs)
{
if (Strings.Left(query.Name, 1) != "~")
{
Debug.Print("Query name = " + query.Name);
// parmaters
foreach (var qParm in query.Parameters)
Debug.Print("query parmater name = " + qParm.Name + " type = " + qParm.Type);
}
}
}
the above will list out each query - and if it has parameters - then it will list out those.

Parameterized query not working in C#

I am currently in a corner and have no idea why the following code will not execute properly and update the database (Access).
newUser = All of the new user's data including their ID
list = Contains a list of GermanResources (class) entries that correspond to the pages checkboxes. Class includes .Name (text value of checkbox) and .Value (checked? 1 or 0)
I want to update the database with the checkbox value of each GermanResource.
IF i replace #acc_Value with the value 1 this code works. It seems to not work with the first parameter in place. Debugging this showed me that everything had the proper values at the proper times and since "1" worked I know the data types are not mismatched.
Note: There were no errors with or without the parameter in place.
I would appreciate any input about this.
This is one of the CommandTexts that are generated:
UPDATE VMS_GRM_GermanResource_Access SET VTOFZN = #acc_Value WHERE UserId = #userId
private bool NewUser_Insert_GermanResourceAccess(OleDbConnection connection, User newUser, List<GermanResource> list)
{
bool result = false;
try
{
foreach (var item in list)
{
string column = item.Name.Replace(" ", "");
string query = #"UPDATE VMS_GRM_GermanResource_Access SET " + column + " = #acc_Value WHERE UserId = #userId";
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#userId", newUser.Id);
command.Parameters.Add(new OleDbParameter("#acc_Value", OleDbType.Integer, 1));
command.Parameters["#acc_Value"].Value = item.Access;
command.ExecuteNonQuery();
}
result = true;
}
catch (OleDbException ex)
{
UADConnection.Close();
MessageBox.Show(ex.ErrorCode.ToString() + ": " + ex.Message);
return result;
}
return result;
}
Use this to prepare sql statement :-
string query = #"UPDATE VMS_GRM_GermanResource_Access SET column_name=" +
#acc_Value + " WHERE UserId = " +#userId+";
#Tetsuya Yamamoto:
OLEDB parameters were not in order according to the query. Swapping them around to match the order in the query set things straight. All good again and thanks for everyone's inputs.

altering table to add unique columns sql ce

I'm trying to add a column on my table using SQL Compact Edition. It used to work before but I am getting an error now that says
A duplicate value cannot be inserted into a unique index. [ Table name = final try,Constraint name = UQ__final try__0000000000000228 ]
i'm using C# because i am getting the new column name (using textbox) and determine if the column is unique(checkbox). it used to work then suddenly it isn't. please help! my code is kinda messy. i'm sorry here it is:
string constr = "ALTER TABLE ";
if (textBox2.Text.ToString() != "")
{
constr += "[" + table + "] ADD [" + col1 + "]";
if (comboBox2.Text == "text")
{
constr += " nvarchar(300)";
}
else if (comboBox2.Text == "number")
{
constr += " int";
}
else if (comboBox2.Text == "date")
{
constr += " datetime";
}
if (checkBox1.Checked)
{
constr += " unique";
}
}
cmd.CommandText = constr;
cmd.ExecuteNonQuery();
The constr outputs something like
ALTER TABLE table ADD COLUMN column1 int unique
Please help! Thanks!
EDIT:
I discovered I cannot add a column only if the data grid view already have its data inside. What should I do? Help! Thanks!!!
I am not familiar with sql server ce but in normal sql server creating a column with the unique keyword means creating an index where no 2 rows can have a null in it because than they are not unique.
So you need to create your column without the unique keyword and than afterwards create an unique index that allows null.
You can create an unique index that ignores null values like this :
CREATE UNIQUE NONCLUSTERED INDEX idx_col1
ON dbo.MyTable(col1)
WHERE col1 IS NOT NULL;

How to fetch 3 column values together from a table

I have a table named CrewMembers which have 3 columns-FirstName,MiddleName and LastName.
I want to fetch the values of these 3 columns together using entity framework in a combobox in this format-
LastName,FirstName MiddleName
Here is the code for the same-
public IEnumerable GetCrewMember()
{
SASEntities db = DataContextFactory.GetSASEntitiesDataContext();
return (from cm in db.CrewMember
select
cm.LastName + "," +
cm.FirstName +" "+
cm.FullName
).ToList();
}
Now when I execute the code,I get only those names in the combobox which have all three values in the table but my MiddleName column can be left Null.Hence,I am not getting full names of those records which doesn't have a MiddleName.
How can I resolve this issue?
do this:
public IEnumerable GetCrewMember()
{
SASEntities db = DataContextFactory.GetSASEntitiesDataContext();
return (from cm in db.CrewMember
select new
{
CompleteName = cm.LastName + ","
+ cm.FirstName +" "
+ cm.FullName
}).ToList();
}

Cannot insert duplicate key row in object with unique index 'in_name'

I get this error: Cannot insert duplicate key row in object with unique index 'in_name'
What can be the problem?
var ing = (from x in db.tblTable where x.ing_name == ing_name select x);
var ing1 = ing.First();
ing1.ing_name = ing1.ing_name + " (" + FormatC(ing_brand) + ")";
db.SaveChanges();
And here is FormatC:
public static string FormatC(string str)
{
if (!string.IsNullOrEmpty(str))
return str.Substring(0, 1).ToUpper() + "" + str.Substring(1).ToLower();
else
return "";
}
Got this answer from - https://www.sqlservercentral.com/forums/topic/cannot-insert-duplicate-key-row-in-object-with-unique-index-on-duplicate-foreing-key
Turns out that SQL Server, by default, sets indexed fields to allow only unique values. To check this, open the table in Design and select "Manage Indexes and Keys" option. Select the index/key listed and check the appropriate Yes/No drop down for the "Is Unique" property.

Categories