Exception while retrieve a null field from sql ce 3.5 - sql

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

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

Making SQL password query case sensitive using COLLATE

I am using the following SQL code in my VB in VS2013. I want to create a login form using a database of users stored into a UserList. However The query is not case sensitive. How do I change my query string to use COLLATE or any other case sensitive comparison
Dim Check As String = _
"SELECT COUNT(*) AS Expr1 FROM UserList HAVING (Username = '" & _
_UsernameTextBox.Text & "') AND ([Password]= '" & _PasswordTextBox.Text & _
"') AND (UserType = '" & User.ToString & "')"
With search
.CommandText = Check
.Connection = cn
If .ExecuteScalar() = 1 Then
Me.Hide()
If User = "Trader" Then
Trader.Show()
ElseIf User = "Broker" Then
Broker.Show()
ElseIf User = "Corporate" Then
Corporate.Show()
ElseIf User = "System" Then
SystemManager.Show()
End If
Else : MsgBox("IncorrectInput")
End If`
"SELECT COUNT(*) AS Expr1 FROM UserList
HAVING (Username = #username)
AND ([Password] COLLATE Latin1_General_CS_AS = #password)
AND (UserType = #usertype)
"
Apart from the fact that you don't have your password stored and compared with a slow salted cryptographic hash function (=non-reversible encryption), your query is also vulnerable to SQL-injection (when I use a username like "Jean le Rond d'Alambert" or just "d'Alambert".
Another bug is that when you save the password as plain text, say e.g. (n)varchar(32), I can enter a password that is longer than that (e.g. a sentence) ==> bug
Given you're writing a financial application ("broker", "corporate"), SQL-injection is an intolerable security risk.
You can for example MD5-hash your password (cheap & dirty):
master.dbo.fn_varbintohexstr(HashBytes('MD5', 'test'))
You have a "System.Data.SqlClient.SqlCommand",
there you can add a System.Data.SqlClient.SqlCommand
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//
// Description of SQL command:
// 1. It selects all cells from rows matching the name.
// 2. It uses LIKE operator because Name is a Text field.
// 3. #Name must be added as a new SqlParameter.
//
using (SqlCommand command = new SqlCommand(
"SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
weight,
name,
breed);
}
}
}
If you do it right from the start, then you don't have to change anything later.

Quick Help: converting SQL to LINQ

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.

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

VB Return a single value from SQL

I am trying to retrieve a single integer value. There will always be one and only one record in the DB for this select. I want to connect, retrieve store and display this value. is this executescalar the way to go?
Dim sqlquery As String
Dim ConnectionString As String
ConnectionString = "Server=" + ServerName + "\" + InstanceName + "; Database=" + DatabaseName + "; User Id=" + UserId + ";Password=" + Password + ";"
sqlquery = "SELECT severity FROM from dbo.SettingsSub where SEB_SettingsID = 'Severity"
'Connect
Using conn As SqlConnection = New SqlConnection(ConnectionString)
conn.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, conn)
CurrentSeverity = Convert.ToInt32(comm.ExecuteScalar())
txtCurrentSeverity.Text = CurrentSeverity
conn.Close()
End Using 'comm
"There will always be one and only one record in the DB for this select."
Even though you know that this is the case you should always use a "Select top 1" statement in this scenario as you never know what will happen in the future.