searching data in a database - sql-server

Here is the aspx.cs file for my web application:
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataReader myDataReader = null;
string connectionString = "Data Source=[my source];Initial Catalog=[catalog name];Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand returnResults = new SqlCommand("SELECT " + categoryName + " FROM Teacher WHERE " + categoryName + " LIKE '%" + searchText + "%'", connection);
connection.Open();
myDataReader = returnResults.ExecuteReader(CommandBehavior.CloseConnection);
while (myDataReader.Read())
{
Console.Write(myDataReader.GetInt32(0) + "\t");
Console.Write(myDataReader.GetString(2) + " " + myDataReader.GetString(1) + "\t");
Console.Write(myDataReader.GetString(3) + "\t");
if (myDataReader.IsDBNull(4))
Console.Write("N/A\n");
else
Console.Write(myDataReader.GetInt32(4) + "\n");
}
myDataReader.Close();
connection.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
categoryName = DropDownList1.SelectedItem.Value;
}
protected void SearchBox_TextChanged(object sender, EventArgs e)
{
searchText = SearchBox.Text;
}
My database has a table with around 24 columns. The DropDownList I have created has an option to select each of these column names. There is a SearchBox underneath where the user can enter a keyword to search.
I want to save the DropDownList selection as "categoryName," and I want to save the SearchBox input as "searchText". When I run the application, I get this error:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'FROM'.
Source Error:
Line 48: myDataReader=returnResults.ExecuteReader(CommandBehavior.CloseConnection);
I'm not sure how to progress from here, so any help is appreciated. If you need more info please ask.

How about this:
SqlCommand returnResults = new SqlCommand("SELECT categoryName FROM Teacher WHERE categoryName LIKE '%" + searchText + "%'", connection);
This is assuming categoryName is the column you want in return, and also the one you want searched. Your original query was doing a few things wrong: using a variable instead of the column name, and the LIKE value wasn't quoted.
If the column to be searched is dynamic, and selected by the drop down box, and the value is stored in the variable categoryName:
SqlCommand returnResults = new SqlCommand("SELECT " + categoryName + " FROM Teacher WHERE " + categoryName + " LIKE '%" + searchText + "%'", connection);

Looks like you may be missing blank spaces
"SELECT" + categoryName + "FROM Teacher WHERE" + searchText + " LIKE " + "%" + searchText + "%", connection);
is going to return something like
SELECTmycolumnnameFROM Teacher WHEREmycolumn LIKE %john%
I think you should do this
"SELECT " + categoryName + " FROM Teacher WHERE " + searchText + " LIKE """ + "%" + searchText + "%""", connection);
to get
SELECT mycolumnname FROM Teacher WHERE mycolumn LIKE "%john%"

Related

I'm getting an error "Incorrect syntax near the keyword 'where' "

I'm trying to update a SQL Server table (connected to a WPF project) and I'm getting the message
Incorrect syntax near the keyword WHERE
What is wrong in my code?
private void Save_button_Click(object sender, RoutedEventArgs e)
{
try
{
Select("INSERT INTO [dbo].[Users](sumScore, doneLevels) VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "') WHERE [userName]= '" + ClsGlobal.userName + "'");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public DataTable Select(string selectSQL)
{
DataTable dataTable = new DataTable("dataBase");
SqlConnection sqlConnection = new SqlConnection(#"Data Source =(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\Avraham\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB\New Database.mdf ");
sqlConnection.Open();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText = selectSQL;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
I'd try to get [and] or (and) near the word username, but this still didn't work.
This query:
INSERT INTO [dbo].Users
VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "')
WHERE [userName]= '" + ClsGlobal.userName;
Does not make sense. INSERT inserts new rows, so WHERE is not appropriate.
Perhaps you want an UPDATE:
UPDATE dbo.Users
SET sumScore = ?,
DoneLevels = ?
WHERE userName = ?;
You should be passing in ClsGlobal.sumScore, ClsGlobal.DoneLevels, and ClsGlobal.userName as parameters rather than munging the query string.

Can I use SQLCLR stored procedure to update a column of a database table

I wanted to update the values of a few columns of a database table, using queries or stored procedure, but wanted to use my C# library to alter the value.
For ex, I want the columns A,B,C of table T to be replaced with Encrypt(A), Encrypt(B) and Encrypt(C) where Encrypt is a part of a C# library.
I could have done it in a simple console application, but I have to do this process for a lot of columns in lot of tables. Could I use some SQLCLR stored procedure/query to do this process in SQL Server Management Studio?
It will be really great if someone could assist in this.
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction()]
public static void Enc()
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
SqlCommand command;
SqlCommand command1;
for (int i = 0; i < 1; i++)
{
command = new SqlCommand("SELECT " + tableFieldArray[i, 1].ToString() + " FROM " + tableFieldArray[i, 0].ToString(), connection);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
if (!reader.IsDBNull(0) && !String.IsNullOrEmpty(reader.GetString(0)))
{
//SqlContext.Pipe.Send("Data = " + reader.GetString(0) + "; Encrypted = " + Encrypt(reader.GetString(0)));
SqlContext.Pipe.Send("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'");
//query = "UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
// + tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
// + "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'";
command1 = new SqlCommand("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'",connection);
}
}
}
SqlCommand command1 = new SqlCommand(query , connection);
command1.ExecuteNonQuery();
}
connection.Close();
}
}
public static string Encrypt(string TextFromForm)
{
//implementation
}
}
}
For some reason this question is a complete duplicate of ( Can I use SQLCLR stored procedure to update a column of a database table ( using some compiled dll) ), but assuming that other one will be closed (it should be), my answer is the same:
You can use SQLCLR to call encryption from C#, though this is the wrong approach. If you need to do a custom algorithm, you should encapsulate that into a SQLCLR function so that it can be used in an UPDATE statement or even an INSERT or SELECT or anywhere. Something like:
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]
public static SqlString EncryptByAES(SqlString TextToEncrypt)
{
return DoSomething(TextToEncrypt.Value);
}
}
Then you can use that function as follows:
UPDATE tb
SET tb.FieldA = EncryptByAES(tb.FieldA)
FROM dbo.TableName tb
WHERE tb.FieldA some_test_to_determine_that_FieldA_is_not_alreay_encrypted;
BUT, before you write a custom encryption algorithm, you might want to check out the several built-in paired ENCRYPTBY / DECRYPTBY functions that might do exactly what you need:
ENCRYPTBYASYMKEY / DECRYPTBYASYMKEY
ENCRYPTBYCERT / DECRYPTBYCERT
ENCRYPTBYKEY / DECRYPTBYKEY
ENCRYPTBYPASSPHRASE / DECRYPTBYPASSPHRASE

how to hide a column in database

This is my original code:
String sqlQuery = "SELECT * FROM data where company = '"+ Selecteditem +"'" ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()){
do{
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code")) +
"," + c.getString(c.getColumnIndex("company"))
);
I want to hide company on the list, I change "*" to name, code but without success, I delete " **"," + c.getString(c.getColumnIndex("company"))** " this line no success,
What to do please help me
You can just remove the company string, by replacing c.getString(c.getColumnIndex("company")) with an empty string "".
String sqlQuery = "SELECT * FROM data where company = '" + Selecteditem + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()) {
do {
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code")) +
"," + ""
);
Another solution is to select only the columnn you need:
String sqlQuery = "SELECT name, code FROM data where company = '" + Selecteditem + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()) {
do {
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code"))
);

missing operator using database (unity3d)

i am using database in my game the query is giving an error of missing operator my code is
public void Execute(){
jsScript = Camera.main.GetComponent(); ReadStudent(Application.dataPath+"/dictionary.accdb","dict","word","word","=",jsScript.words);
}
internal void ReadStudent(string filetoread,string tableName, string itemToSelect, string wCol, string wPar, string wValue){
string connection = "Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=" + filetoread;
Debug.Log(connection);
string sqlQuery ="SELECT word FROM"+ tableName +"WHERE" + wCol + wPar+"'"+wValue+"";
OdbcConnection con = new OdbcConnection(connection);
OdbcCommand cmd = new OdbcCommand(sqlQuery,con);
DataTable dt = new DataTable("dic");
try{
con.Open();
OdbcDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
reader.Close();
con.Close();
}
catch (Exception ex){
//text = dt.Rows[3][1].ToString();
Debug.Log(ex.ToString());
}
finally{
if (con.State!=ConnectionState.Closed){
con.Close();
}
con.Dispose();
}
if (dt.Rows.Count>0){
text = dt.Rows[0]["word"].ToString();
}
}
it is giving error : System.Data.Odbc.OdbcException: ERROR [42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'word FROMdictWHEREword='MX'.
As evident by the error, your SELECT statement is lacking spaces:
[SELECT] 'word FROMdictWHEREword='MX'.
This malformed SQL is created by the following line:
string sqlQuery ="SELECT word FROM"+ tableName +"WHERE" + wCol + wPar+"'"+wValue+"";
Just add the spaces to it, and you should be fine:
string sqlQuery = "SELECT word FROM "+ tableName + " WHERE " + wCol + " " + wPar + " '" + wValue + "'";
It looks as though you're missing spaces from the command:
select word FROMdictWHEREword='MX'
should read something like
select word FROM dict WHERE word = 'MX'

sql insert method fails when using ecrypted string

I'm using md5 to ecnrypt the user password. But whenever I try to add any records my code is throwing an error "Syntax error in INSERT INTO statement."
Here's my code
public int InsertUser(string lastName, string firstName, string username, string password, bool isAdmin)
{
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
string encryptPassword = encryptMD5(username,password).ToString();
OleDbCommand dCmd = new OleDbCommand("INSERT INTO Users (LastName, FirstName, UserName, Password) " +
"VALUES ('" + lastName + "','" + firstName + "','" + username + "','" + encryptPassword + "')", conn);
dCmd.CommandType = CommandType.Text;
try
{
return dCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
private string encryptMD5(string username, string sPassword)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(sPassword + username);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}
Try this below, it ensure that all parameters are properly enclosed and escaped.
try
{
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
string encryptPassword = encryptMD5(username, password).ToString();
using (OleDbCommand dCmd = new OleDbCommand(
"INSERT INTO Users (LastName, FirstName, UserName, Password) " +
"VALUES (?, ?, ?, ?)", conn))
{
dCmd.CommandType = CommandType.Text;
OleDbParameter p;
dCmd.Parameters.Add(p = new OleDbParameter("#lastName", OleDbType.VarChar));
p.Value = lastName;
dCmd.Parameters.Add(p = new OleDbParameter("#firstName", OleDbType.VarChar));
p.Value = firstName;
dCmd.Parameters.Add(p = new OleDbParameter("#username", OleDbType.VarChar));
p.Value = username;
dCmd.Parameters.Add(p = new OleDbParameter("#encryptPassword", OleDbType.VarChar));
p.Value = encryptMD5(username, password);
return dCmd.ExecuteNonQuery();
}
}
}
catch
{
throw; // here should be better exception handling
}
You have a problem of higher level.
You should never create a SQL statement by concatenation of statement and values. You should bind values as parameters, then underlying framework will handle parameters and even provide them separately from the SQL statement to the server. It is much more secure way (no SQL injection is possible), with better performance and you will not get into these types of error.
If you want to understand the reason for the problem, then you should look into the actual insert statement you create and the problem will become obvious
"INSERT INTO Users (LastName, FirstName, UserName, Password) " + "VALUES ('" + lastName + "','" + firstName + "','" + username + "','" + encryptPassword + "')"
It is likely that the result of your MD5 hash or other parameters somehow breaks the SQL INSERT syntax. (it should not in most of the cases, you should provide the actual values)
You should try to execute the resulting query on the actual database to see the actual error in returns (use SQL Server Management Studio for example)
To bind parameters you should use something like that:
dCmd.Parameters.Add(new OleDbParameter("#username",username));
See some MSDN reference: OleDbCommand Parameters

Resources