Quick Help: converting SQL to LINQ - sql

How do you convert this SQL to LINQ?
I'm reading it now, but just putting this out there in case I can't do it.
SqlConnection connection = new SqlConnection
{
ConnectionString = ConfigurationManager.ConnectionStrings["HBOS"].ConnectionString
};
connection.Open();
foreach (ExchangeRateData x in exchangeRateDatas.ExchangeRateDataList)
{
SqlCommand cmd = new SqlCommand("UPDATE dbo.CurrencyExchange " +
"SET Rate = '" + x.Rate + "', DateTimeStamp = CAST('" + x.TimeStamp +
"' AS DATETIME), CreatedBy = '" + x.CreatedBy + "', RateInv = '" +
x.RateInv + "' " +
"WHERE Currency = '" + x.ToCurrency + "';", connection);
// Sql query and connection
cmd.ExecuteNonQuery();
}
connection.Close();

Create a dbcontext first
then
CurrencyExchange CurrencyExchangeObject = context.CurrencyExchange
.Where(a => a.Currency = x.ToCurrency)
.FirstOrDefault();
after that you can simple assign the values
like
CurrencyExchangeObject.Rate = x.Rate;
CurrencyExchangeObject.DateTimeStamp = Convert.ToDateTime(x.TimeStamp);
and then simply say
context.SaveChanges();

Sounds like your boss is looking for a LINQ to SQL implementation. Unfortunately, your question does not have a quick answer because adding this functionality requires a lot more than just "converting a query to LINQ", as there are a number of things needed to get your environment set up to support it.
You may want to start with some basic Googling of the topic:
First couple results:
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
http://msdn.microsoft.com/en-us/library/bb386976(v=vs.110).aspx
LINQ to SQL has a more widely-used cousin called Entity Framework, which is not dependent upon SQL Server. You may want to consider that as well.

Related

How to execute 2 SQLlite Queries with single command

I need to execute 2 sql queries here. for this purpose i have using 2 sqlcommands here.but I think that it is not the right way. Code duplication is the main prbl.so how to Handel this. Or this is the right way?
string UserStatus = "update Users SET Status=0";
SQLiteCommand setStatusCmd = new SQLiteCommand(StatusQuery);
setStatusCmd.CommandType = CommandType.Text;
setStatusCmd.Connection = sqlconnection;
setStatusCmd.ExecuteNonQuery();
string UpdateQuery = ("UPDATE Users SET password ='" + password + "', + "' WHERE name = '" + userName + "'; ");
SQLiteCommand updateCmd = new SQLiteCommand(userUpdateQuery);
updateCmd.CommandType = CommandType.Text;
updateCmd.Connection = sqlconnection;
updateCmd.ExecuteNonQuery();

Can you pass more than 1 parameter in a single SQL statement through a VB command?

Just wondering can you pass 2 parameters ( #Insertparanamehere ) in 1 sql command via VB? I have some code below ( sample code ) and I am just wondering is this possible.
Command = New SqlCommand("Update Boards Set CDF_Supplier_Tx='" + SupplierNameTxt.Text + "' Where CDF_Supplier_tx IN ( Select Supplier From Suppliers Where Supplier = '" + SupplierNameTxt.Text + "')", connection)
Where it says '" + SupplierNameTxt.Text + "' could this be potentially replaced with #Insertnameparaname from here?
If this is unclear as to which I will try to explain this a little more so my code would end up with 2x# instead of the long supplierNameTxt.Text?
This is just a question , thank you in advance.
MyCommand = New SqlCommand("UPDATE SeansMessage SET Message1 = #TicBoxText1, Message2 = #TicBoxText2 WHERE Number = 1", dbConn)
MyCommand.Parameters.AddWithValue("#TicBoxText1", TicBoxText1.Text)
MyCommand.Parameters.AddWithValue("#TicBoxText2", TicBoxText2.Text)
See here:
How to use parameters "#" in an SQL command in VB
You can also use the same parameter multiple times in your SQL text.

Error with SQL command

I'm trying to get the users details in the text boxes in my form to my database in access, which should save. However i keep getting an error message every time i click to register, the following code is how i am trying to write it out:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
However I think that the problem is actually coming from this section:
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
Really your query is unreadable. Any kind of error could hide in that jungle of string concatenation and single quotes sprawled everywhere. (like a not necessary comma escaped probably from a fixup of a copy/paste operation)
You should use parameterized query and all of this will disappear
command.Connection = connection;
string sql = "UPDATE enroll SET SSN=?, Name=?, Company=? WHERE ID=?";
command.CommandText = sql;
command.Parameters.AddWithValue("#p1", txtSSN.Text);
command.Parameters.AddWithValue("#p2", txtName.Text );
command.Parameters.AddWithValue("#p3", txtCompany.Text);
command.Parameters.AddWithValue("#p4", _UserID);
command.ExecuteNonQuery();
Now I think that this is really more readable, no quotes to add because the framework knows the datatype of every parameter and will use the appropriate quoting required. Last but not least, no problem with Sql Injection

Object reference not set to an instance of an object and 'there is no available code source' errors

sqlcom1 = New SqlCommand("INSERT INTO Products VALUES ('" +
ds.Tables("Products_Archive").Rows(myval).Item(1) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(2) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(3) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(4) + "','" +
ds.Tables("Products").Rows(myval).Item(5) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(6) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(7) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(8) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(9) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(10) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(11) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(12) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(13) + "','" +
ds.Tables("Products_Archive").Rows(myval).Item(14) + "', '" +
ds.Tables("Products_Archive").Rows(myval).Item(15) + "')", con1)
sqlcom1.ExecuteNonQuery()
This is my code. I get the error
Object reference not set to an instance of an object.
and there is a message box saying "There is no available code source...' What should solve this problem?
You should use parametrized queries for ADO.NET - ALWAYS - to avoid SQL injection attacks and to improve performance.
And when assigning values from your DataSet, you need to check for NULL before blindly assigning the value!
So try something like this:
// define your SQL statement - with **PARAMETERS**
// first off: I would recommend to ALWAYS define the columns in the table that you want to insert into
// to avoid unpleasant surprises (if e.g. a new column is added); of course, use YOUR column
// names from the "Products" table here! Since you didn't give them - I had to fill in "placeholders"
// secondly: use **PARAMETERS** in your INSERT statement! One for each column you want to insert a value into.
// Again: you should use "#YourColumnName" for each column in your table - since I don't know
// those column names - I just made up placeholders. Replace those as needed!
string sqlStmt = "INSERT INTO dbo.Products(Col1, Col2, ..., Col15) " +
"VALUES(#v1, #v2, ....., #v15)";
// create SqlConnection and SqlCommand to use
using(SqlConnection conn = new SqlConnection("......"))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
// fetch the DataTable you use, and the current row in that table
DataTable tbl = ds.Tables["Products_Archive"];
DataRow currentRow = tbl.Rows[myval];
// define the parameters and set their values
cmd.Parameters.AddWithValue("#v1", GetValue(currentRow, 1));
cmd.Parameters.AddWithValue("#v2", GetValue(currentRow, 2));
.....
cmd.Parameters.AddWithValue("#v15", GetValue(currentRow, 15));
// open connection, execute query, close connection
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
// method to fetch the value from the row
private object GetValue(DataRow row, int index)
{
// CHECK FOR NULL ! If the value is NULL - define what you want to have returned.
if(IsNull(row[index]))
{
// return whatever makes sense to you, if the value in the DataTable's row is NULL
// here - I chose to return a "database NULL" so that NULL will be inserted into the database
return DbNull.Value;
}
// only if NOT NULL --> then return the actual value in that row's column
return row[index];
}

Exception while retrieve a null field from sql ce 3.5

I am storing an image in a table in varbinary(max) format, actually first time it will be empty, I am checking whether it is empty of not but while checking for null field I am getting any exception stating invalid cast so can any one suggest what is the problem with this.
code sample is
con = new SqlCeConnection(CommonClass.ConnectionStringStartup);
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT Signature,UserId FROM UserMaster Where " +
" LoginName = '" + UserName + "' " +
" AND Password = '" + Password + "'";
cmd.CommandType = CommandType.Text;
// MessageBox.Show(UserName);
SqlCeDataReader dr;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
if (dr.IsDBNull(0))
SignLoaded = false;
else
SignLoaded = true;
}
Thanks in advance
With regards
Bharath kumar
To me, it looks like this should work?
Have you tried Convert.IsDbNull( dr.GetValue(0))?
Otherwise I can only suggest using dr.GetValue(0) and look at the result.
Cheers