I wrote a method to delete values from a database, however when I check the rows affected the value is 0 and keeps going into the first if statement any ideas?
private void workstationDelete()
{
string query = "DELETE FROM test_revision2 where wsid = #wsid and location = '#location'";
try
{
conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#wsid", Convert.ToInt32(wsid2text.Text));
cmd.Parameters.AddWithValue("#location", deletelocation);
cmd.ExecuteNonQuery();
int rowsaffected = cmd.ExecuteNonQuery();
if (rowsaffected == 0)
{
lblDel.Text = "Sorry Workstation: " + wsid2text.Text + " does not exist in " + deletelocation + ". Therefore it cannot be removed.";
}
else
{
lblDel.Text = "You have successfully removed Workstation: " + Convert.ToInt32(wsid2text.Text) + " in " + deletelocation;
}
conn.Close();
}
catch (SqlException)
{
lblDel.Text = "randome";
}
}
Remove the single quotation marks from '#location'. You have it ignoring the parameter and trying to match a string literal.
Aside: There are good reasons not to use AddWithValue.
The problem was I was using cmd.executeNonQuery twice the first one was returning 1 however when I initialized to a var it becomes 0. Use execute non query once - when assigning the int var.
Related
I want to know, how to implement the text qualifier while importing using script task. Below is my code. I have been only able to use delimiter and not text qualifier. So, I am also getting double quotes loaded in my table.
public void Main()
{
// TODO: Add your code here
string SourceFolderPath = Dts.Variables["User::SourceFolder"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string TableName = Dts.Variables["User::DestinationTable"].Value.ToString();
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)
(Dts.Connections["PEGASUS.AdventureWorks1"].AcquireConnection(Dts.Transaction) as SqlConnection);
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach (string fileName in fileEntries)
{
int counter = 0;
string line;
string ColumnList="";
MessageBox.Show(fileName);
System.IO.StreamReader SourceFile = new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
ColumnList = "[" +(line.Replace(FileDelimiter, "],[").Replace("\"", ""))+ "]";
MessageBox.Show(ColumnList.ToString());
}
else
{
MessageBox.Show("pass 2");
string query = "Insert into " + TableName + " (" + ColumnList + ") ";
query += "VALUES('" + line.Replace(FileDelimiter, "','") + "')";
MessageBox.Show("pass 3");
//MessageBox.Show(query.ToString());
SqlCommand cmd = new SqlCommand(query, myADONETConnection);
cmd.ExecuteNonQuery();
MessageBox.Show("pass 4");
}
counter++;
}
SourceFile.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
above are the input and expected output.
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'
I've googled this found a few useful sites that have helped me out but not sure exactly what is going wrong. I have my database with data in it. I can display data on the page load and I can sort through the data with next and previous buttons, but the issue is my find button is not working and always display my "no rows found" message when searching for a name. I'm sure there is a more efficient way to do this but havent looked in to that just yet.
Thanks
Here is my code:
string searchFor = txtSearch.Text.Trim();
int results = 0;
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\AddressBook.mdb");
conn.Open();
DataSet ds = new DataSet();
string cmd = "SELECT * FROM tblAddressBook";
OleDbDataAdapter da = new OleDbDataAdapter(cmd, conn);
da.Fill(ds, "Info");
DataRow[] returedRows;
DataRow dr;
returedRows = ds.Tables.Select("LastName=' " + searchFor + " ' ");
results = returedRows.Length;
if (results > 0)
{
dr = returedRows[0];
txtFirstName.Text = dr["FirstName"].ToString();
txtLastName.Text = dr["LastName"].ToString();
txtEmail.Text = dr["Email"].ToString();
txtPhone.Text = dr["PhoneNumber"].ToString();
}
else
{
lblReturned.Text = "No Rows Found";
}
//close the connection
conn.Close();
Your .Select string is adding a space to the beginning and end of the search term. If searchFor contained Thompson then your statement would be
.Select("LastName=' Thompson ' ")
so no entries would match unless they had a leading space. Also, I had no idea what ds.tblAddressBook had to do with anything so I just used this instead:
returedRows = ds.Tables["Info"].Select("LastName='" + searchFor + "'");
Now you need to tweak your code so it won't blow up when somebody tries to search for O'Connor.
I am trying to write a Windows Form program on top of .NET 4.0 and accessing Microsoft Access Database. I can read and write with no problem but sometimes, I get this error:
COM object that has been separated from its underlying RCW cannot be used.
I tried to call this method (GetIDBasedonTeamName) with different inputs twice (on the same thread). The second time this is run, I got that error.
OleDbConnection conn = new OleDbConnection();
OleDbConnection mDB = new OleDbConnection();
OleDbCommand comm = new OleDbCommand();
OleDbCommand cmd;
OleDbDataReader dr;
public void OpenConnection(string name) // always call this method first in other methods to initialise connection
{
conn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
conn.Open();
comm.Connection = conn;
comm.Parameters.Clear();
}
public string GetIDBasedonTeamName(string teamName)
{
string toReturn = "";
try
{
OpenConnection("form");
comm.CommandText = "Select ID from TeamDetails WHERE TeamName=#teamName";
comm.Parameters.AddWithValue("TeamName", teamName);
dr = comm.ExecuteReader();
while (dr.Read())
{
toReturn = dr[0].ToString();
}
}
catch (OleDbException e)
{
string err = e.Message.ToString();
return null;
}
finally
{
}
conn.Close();
dr.Close();
return toReturn;
}
Exception happened on dr = comm.ExecuteReader();.
The method that was calling this method have this 2 lines inside:
InfoConfig.team1id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam1.Text));
InfoConfig.team2id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam2.Text));
What could be the cause? I read around and they mentioned not to use different threads but it is the same thread here.
Thanks,
Guo Hong
Building on Martin Liversage's answer:
public string GetIDBasedonTeamName(string teamName) {
var connString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
using (var conn = new OleDbConnection(connString)) {
conn.Open();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText="Select ID from TeamDetails WHERE TeamName = #teamName";
cmd.Parameters.AddWithValue("TeamName", teamName);
using (var rdr = cmd.ExecuteReader()) {
if (rdr.Read()) {
return (string)rdr["TeamName"];
}
//if no valid results will return null
}
}
}
}
Instead of creating the objects only once and storing them in fields in your class you should create, use and close the objects in your method. It is probably the Close you call in the end the method that releases the underlying COM objects giving you the exception on the second call.
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