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'
Related
Good day !
OK so I've made researches to find a solution to my problem, and tried everything and still...
I have to upload records from Excel to SQL Server. First I created a SQL Connection Manager, with the dynamic variable #[User::FilePath] as an expression, and it was working perfectly... until this morning !
Error message:
Error: 0xC0202009 at CriticalList, Connection manager "Excel Connection Manager": SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available. Source: "Microsoft Access Database Engine" Hresult: 0x80004005 Description: "External table is not in the expected format.".
Error: 0xC020801C at Load Input file into Staging table, Excel Source 1: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0202009. There may be error messages posted before this with more information on why the AcquireConnection method call failed.
Error: 0xC0047017 at Load Input file into Staging table, SSIS.Pipeline: Excel Source failed validation and returned error code 0xC020801C.
Here is how I setup my connection:
Since, I tried to :
Set the ConnectionString as an expression instead of the FilePath as follow:
“Provider=Microsoft.ACE.OLEDB.12.0; User ID=;Data Source=” + #[User::FilePath] + “;Extended Properties="EXCEL 12.0;HDR=YES;IMEX=1";”
Create an OLE DB Connection instead (Provider=Microsoft.ACE.OLEDB.12.0), but I didn't find the way to pass the FilePath.
Please note that the account that I am using has access to all of the directories where the files are located. Can somebody help me with this please ? My deadline is in two weeks, and I am stuck with this :-(
Thanks a lot in advance for your help.
Mylene
I updated the package to use bulk insert (ADO Connection) in a script task. It' working perfectly.
Here is the CSharp code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//drop Excel file if exists
File.Delete(FolderPath + "\\" + ExcelFileName + ".xlsx");
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
}
I want to load sql query(Number of column change every time)data in Excel workbook that create column header dynamically.
First i have create four variable
Table Customer_NA have some entries
And create Ado.net connection and configure server-name and database name
Drag Script task and and assign all 4 variable in ReadOnlyVariable.
Edit Script task and write code to generate excel sheet column dynamically
public void Main()
{
// TODO: Add your code here
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["User::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
string TableName = Dts.Variables["User::TableName"].Value.ToString();
string SheetName = Dts.Variables["User::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.16.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//drop Excel file if exists
File.Delete(FolderPath + "\\" + ExcelFileName + ".xlsx");
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["Ado_Conn"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT * from " + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//MessageBox.Show(TableColumns);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::FolderPath"].Value.ToString() + "\\" +
Dts.Variables["User::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Same Ado_Conn connection name i have write in c# script still facing error
after successfully buid script and run package and got error
Please help me out
I hope i Explain the scnerio
The alert shows a generic error message, therefore it is not possible to pinpoint the cause of the error.
Consider to add this line into a CATCH block:
Dts.Events.FireError(0, "Script Task Example", exception.Message + "\r" + exception.StackTrace, String.Empty, 0);
Also, perhaps it makes sense, for now, temporarily disable writing logs into a custom log file since this operation by itself can cause errors and they will not be captured by try..catch...
So the edited version will look this way:
catch (Exception exception)
{
Dts.Events.FireError(0, "Script Task", exception.Message + "\r" + exception.StackTrace, String.Empty, 0);
// Create Log File for Errors
// using (StreamWriter sw = File.CreateText(Dts.Variables["User::FolderPath"].Value.ToString() + "\\" +
// Dts.Variables["User::ExcelFileName"].Value.ToString() + datetime + ".log"))
// {
// sw.WriteLine(exception.ToString());
// Dts.TaskResult = (int)ScriptResults.Failure;
// }
}
The real reason of the exception will be routed to SSIS logs and can be tracked via SSDT output window or native SSIS Catalog logging in case if the package is deployed to a server
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.
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
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%"