Only one OleDBParemeter is replaced in SQL Query - c#

I am currently working on accessing a database using OleDB and I am having issue with string replacement of OleDBParameter.
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM " + tablename + " WHERE ID = #ID ;";
cmd.Parameters.AddWithValue("#ID", testslist.number + "_" + testcase.name + "_" + testcase.config);
OleDbDataReader reader = cmd.ExecuteReader();
RecordExists = reader.HasRows;
reader.Close();
if (RecordExists)
{
string updatestring = null;
foreach (KeyValuePair<string, string> kv in dictionary)
updatestring = updatestring + kv.Key + " = '#val" + kv.Key + "',";
cmd.CommandText = "UPDATE " + tablename + " SET " + updatestring.Remove(updatestring.Length - 1) + " WHERE ID = #ID;";
foreach(KeyValuePair<string,string> kv in dictionary)
{
if (kv.Value == null)
cmd.Parameters.AddWithValue("#val" + kv.Key, DBNull.Value);
else
cmd.Parameters.AddWithValue("#val" + kv.Key, kv.Value);
}
cmd.ExecuteNonQuery();
}
else
{
string insertstring = "ID,";
string valuestring = "#ID,";
foreach(KeyValuePair<string,string>kv in dictionary)
{
insertstring = insertstring + kv.Key + ",";
valuestring = valuestring + "#var" + kv.Key + ",";
// valuestring = valuestring + "'"+ kv.Value+ "',";
}
cmd.CommandText = "INSERT INTO " + tablename + " (" + insertstring.Remove(insertstring.Length - 1) + ") VALUES(" + valuestring.Remove(valuestring.Length - 1) + ");";
foreach (KeyValuePair<string, string> kv in dictionary)
{
if (kv.Value == null)
cmd.Parameters.AddWithValue("#val" + kv.Key, DBNull.Value);
else
cmd.Parameters.AddWithValue("#val" + kv.Key, kv.Value);
}
cmd.ExecuteNonQuery();
}
For whatever reason, only the #ID is getting replaced correctly in my database. After running the code, the ID is replaced correctly in my database, but every other field values are #var[nameofthekey] (#varTestCase for example) . I really don't know where to look anymore especially since one the parameter gets replaced properly in the database, but not the other.
Thank you for your help!
edit: I forgot to mention, I am working with an access database (accdb)

Related

How do I show the last 10 rows in the table?

private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
while (reader.Read() == true && result.Count <= 9 )
{
if (reader.GetString(1) == "0")
{ //+ "ficando assim com: " + reader.GetDecimal(3)
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
return result;
}
}
}
private static IEnumerable<string> extratoOperacao(string numeroCartao)
{
return getExtrato($#"SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'");
}
As I have is presenting me only the first 10 lines, but I need the last 10 by normal order, how do I do that?
If anyone can help me, I'd be grateful
private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
// Let's remove unused conditions
while (reader.Read())
{
if (reader.GetString(1) == "0")
{
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
// HERE IS THE MAGIC
return result.TakeLast(10);
}
}
}
If you use an ORDER BY in the query you can make sure which records are returned, and you can use TOP to restrict the quantity of records returned, so something like
return getExtrato($#"SELECT TOP 10 [CardNumber], [Deposit], [Withdraw], [DataHora], [Id] FROM [MoveInfo] WHERE [CardNumber] = '{numeroCartao}' ORDER BY [Id] DESC");
will return the desired records, and then you just need to read all of them and reverse the result in your code (there are other possibilities, but that might be simplest for now).

C# Asp.net Webforms simple SQL Query for 1 row several columns to variables

I have been searching around and I am either confusing myself or not searching for the right thing.
I have this data reader that pulls some information for a store procedure.. but I don't think I am doing it right.
string constr = ConfigurationManager.ConnectionStrings["PAYROLL"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DLI_EMPLOYEE_PORTAL_EMPLOYEE_INFORMATION"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EID", Session["sessionEMPID"].ToString());
cmd.Connection = con;
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dataReader.Read())
{
string EMP_FIRST = dataReader["FIRST_NAME"].ToString();
string EMP_LAST = dataReader["LAST_NAME"].ToString();
string EMP_DEPT = dataReader["DEPT"].ToString();
string EMP_DEPT_ID = dataReader["DEPT_ID"].ToString();
body = body + "<p>SUBMITTED BY : (" + Session["sessionEMPID"].ToString() + ") " + EMP_FIRST + " " + EMP_LAST + " - DEPT : " + EMP_DEPT + "</p> " + System.Environment.NewLine;
}
con.Close();
}
}
I just need to query one row based of an employee ID.. and I would rather do it not by stored procedure but a select query.
SELECT e.FIRST_NAME, e.LAST_NAME, e.DEPT_ID, d.NAME
FROM EMPLOYEE AS e
INNER JOIN DEPARTMENT AS d ON e.DEPT_ID = d.ID
WHERE (e.ID = 'sim01')
I am building an HTML body string so that is why I need the information.
body = body + "<p>SUBMITTED BY : (" + Session["sessionEMPID"].ToString() + ") " + EMP_FIRST + " " + EMP_LAST + " - DEPT : " + EMP_DEPT + "</p> " + System.Environment.NewLine;
Any help is greatly appreciated. Thank you.
If all you want to do is use a query instead of a stored procedure, just pass your SQL statement to the Command and set your CommandType to Text. If you only ever expect one row, use if (dataReader.Read() instead of while (dataReader.Read()).
string constr = ConfigurationManager.ConnectionStrings["PAYROLL"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(
"SELECT e.FIRST_NAME, e.LAST_NAME, e.DEPT_ID, d.NAME " +
"FROM EMPLOYEE AS e " +
"INNER JOIN DEPARTMENT AS d ON e.DEPT_ID = d.ID " +
"WHERE (e.ID = #EID)"));
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EID", Session["sessionEMPID"].ToString());
cmd.Connection = con;
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dataReader.Read())
{
string EMP_FIRST = dataReader["FIRST_NAME"].ToString();
string EMP_LAST = dataReader["LAST_NAME"].ToString();
string EMP_DEPT = dataReader["DEPT"].ToString();
string EMP_DEPT_ID = dataReader["DEPT_ID"].ToString();
body = body + "<p>SUBMITTED BY : (" + Session["sessionEMPID"].ToString() + ") " + EMP_FIRST + " " + EMP_LAST + " - DEPT : " + EMP_DEPT + "</p> " + System.Environment.NewLine;
}
con.Close();
}
}
If the query can return more than one row, you can add TOP 1 to the query with an ORDER BY <some other field> to grab only the most relevant one.
It us better to use query instead of stored procedure if there is no TSQL logic

SSIS Import Multiple Files and Create Tables

I'm using SSIS and am importing multiple (30) txt files. I create the table on the fly using the file name of the txt file and creating the columns based on the first row from the txt file - all this works. My code stops working when an apostrophe ' is in one of the fields.
The files are delimitated using a |
My code:
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["xxxxxxxxxxxxxx"].AcquireConnection(Dts.Transaction) as SqlConnection);
string line1 = "";
//Reading file names one by one
string SourceDirectory = #"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string[] fileEntries = Directory.GetFiles(SourceDirectory);
foreach (string fileName in fileEntries)
{
// do something with fileName
string columname = "";
//Reading first line of each file and assign to variable
System.IO.StreamReader file2 =
new System.IO.StreamReader(fileName);
string filenameonly = ((((fileName.Replace(SourceDirectory, "")).Replace(".txt", "")).Replace("\\", "")).Replace("-", "_"));
line1 = (" IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo]." + filenameonly + "') AND type in (N'U'))DROP TABLE [dbo]." + filenameonly + " Create Table dbo." + filenameonly + "([" + file2.ReadLine().Replace("|", "] NVARCHAR(500),[") + "] NVARCHAR(500))").Replace(".txt", "");
file2.Close();
SqlCommand myCommand = new SqlCommand(line1, myADONETConnection);
myCommand.ExecuteNonQuery();
MessageBox.Show("TABLE IS CREATED");
//Writing Data of File Into Table
int counter = 0;
string line;
System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
columname = line.ToString();
columname = "[" + columname.Replace("|", "],[") + "]";
}
else
{
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','") + "')";
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}
counter++;
}
SourceFile.Close();
The offending line is:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','") + "')";
I tried amending to the below to replace the apostrophe to no avail:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','") + line.Replace("'''", "") + "')";
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("'", "") + "')";
Also nesting the replace does not work:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace(line.Replace("'''", ""),"|" ) + "')";
The below does not import anything:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','").Replace("'", "") + "')";
Changing to the below imports all but then fails over at the line with the apostrophe:
string query = "Insert into dbo." + filenameonly + "(" + columname + ") VALUES('" + line.Replace("|", "','").Replace("'''", "") + "')";
What am I missing?
Instead of concatenating the two REPLACE() functions like your first attempt, you should nest them.
Replace(
Replace({arguments to remove apostrophe character}),
{arguments to remove pipe character}
)
If you want to keep the C# usage of string.Replace(), you would nest like this:
line.Replace({arguments to replace apostrophe).Replace({arguments to replace pipe})
Or you could do it in two separate statements:
line = line.Replace({arguments to replace apostrophe});
line = line.Replace({arguments to replace pipe});

c# get the DataType and Size of a column

public DataTable InsertToIncludeandReturnErrorTable(DataTable MappingTable, DataTable InsertTable, string TableName)
{
//split data and insert data to datatable and validation
var CS = Serenity.Data.SqlConnections.GetConnectionString("Northwind");
String MyConString = CS.ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = MyConString;
DataTable returnDataTable = InsertTable.Clone();
con.Open();
foreach (DataRow InsertRow in InsertTable.Rows)
{
try
{
string InsertDBFileld = "";
string DatarowField = "";
foreach (DataRow row in MappingTable.Rows)
{
if (InsertDBFileld == "")
InsertDBFileld = InsertDBFileld + row["TableColumn"].ToString().Replace("\r\n", "");
else
InsertDBFileld = InsertDBFileld + "," + row["TableColumn"].ToString().Replace("\r\n", "");
if (DatarowField == "")
DatarowField = "'" + DatarowField + InsertRow[row["ExcelColumn"].ToString().Replace("\r\n", "")].ToString() + "'";
else
DatarowField = DatarowField + ",'" + InsertRow[row["ExcelColumn"].ToString().Replace("\r\n", "")].ToString() + "'";
}
InsertDBFileld = InsertDBFileld + #",CreatedBy,CreatedDate,ModifiedBy,ModifiedDate";
DatarowField = DatarowField + ",'" + User.Identity.Name + "'," + "'" + DateTime.Now + "'," + "'" + User.Identity.Name + "'," + "'" + DateTime.Now + "'";
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO dbo." + TableName + #"(
" + InsertDBFileld + #"
) VALUES(" + DatarowField + ")", con))
{
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
DataRow returnRow = InsertRow;
returnDataTable.Rows.Add(InsertRow.ItemArray);
}
}
if (con.State == System.Data.ConnectionState.Open)
con.Close();
return returnDataTable;
}
[HttpGet]
public FileContentResult DownLoadFile(string destFilePath)
{
//Generate Excel file with data
destFilePath = destFilePath.Replace("%5c", "\\").Replace("%3a", ":");
byte[] fileBytes = System.IO.File.ReadAllBytes(destFilePath);
string fileName = "ErrorList.xlsx";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Orginal Code can detect the column data length and output wrong data row.
How can I get the DataType and Size of a column?
If I upload a excel exceed the data length, output a excel file and fill in the red color in the wrong data cell.
You can check the data type and maximum length from the columns of your DataTable:
Type columnType = InsertTable.Columns["TableColumn"].DataType;
int maxLength = InsertTable.Columns["TableColumn"].MaxLength;
If your table does not include schema information (which I doubt), you can get the schema first from the database with a SqlDataAdapter. The FillSchema method is what you need.

get different column value from two tables which has same primary key in c#

I have two tables with same name/schema but with different values.
I need to find the row which has same primary key(1st column) but different values.
ex.
my-table:
id name age
1 ram 25
2 mohan 30
my-table:
id name age
3 harry 26
**1 ram 35**
3 tony 45
So I need 2 row from 2 table with value 35.
It should return whole row as data table or data row.
I am using oracle database. needed c# code for this solution.
and it should work for multiple column values for other tables also.
my code..
public OracleCommand getColumns(OracleConnection connection, DataTable table, int i, string tab, DataTable table3)
{
int columCount = table.Columns.Count;
string [] colArray = new string[columCount];
string pkey = table.Columns[0].ColumnName;
string pkeyValue = table.Rows[i][0].ToString();
string query2 = "SELECT * FROM " + tab +
" WHERE " + tab + "." + pkey + " = '" + pkeyValue + "'";
OracleCommand command = new OracleCommand();
int k = 0;
int X =0;
for(int j=1 ; j<colArray.Length;j++)
{
string column = table.Columns[j].ColumnName;
string columnValue = table.Rows[i][j].ToString();
string add = " OR " + tab + "." + column + " = '" + columnValue + "'";
query2 += add;
command.CommandText = query2;
command.CommandType = CommandType.Text;
command.Connection = connection;
var check = command.ExecuteNonQuery();
if (check == null)
{
k++;
}
else
X++;
}
return command;
}
Here is example for your tables, I am presenting data from t2 which do not match rows in t1:
using Oracle.DataAccess.Client;
...
public string OraText(string pkey, string[] tables, string[] columns)
{
string sSQL = "select " + pkey + "";
foreach (string s in columns)
{
sSQL += ", " + tables[1] + "." + s;
}
sSQL += Environment.NewLine + " from t1 join t2 using (" + pkey + ") "
+ Environment.NewLine + " where 1=0 ";
foreach (string s in columns)
{
sSQL += " or " + tables[0] + "." + s + " <> " + tables[1] + "." + s;
}
return sSQL;
}
private void Form1_Load(object sender, EventArgs e)
{
OracleConnection oc = new OracleConnection(
"User Id=scott;Password=tiger;Data Source=XE");
oc.Open();
string[] tables = {"t1", "t2"};
string[] columns = {"name", "age"};
string sSQL = OraText("id", tables, columns);
OracleCommand oracmd = new OracleCommand(sSQL, oc);
OracleDataReader reader = oracmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0) + " "
+ reader.GetValue(1) + " " +reader.GetValue(2));
}
oc.Close();
}
Console output:
1 ram 35

Categories