How to query a C# list against a database table - c#

My code isn't returning any rows from a test database table when I pass a string version of a list, but it does return rows if I pass the list members in directly.
When I use a message box to show the string joinedSerialsList, it appears to be formatted properly.
// Create comma delimited list of serials:
int currentSerial = beginning;
List<string> serialsList = new List<string>();
for (int i = 0; i < count; i++)
{
serialsList.Add(currentSerial.ToString());
currentSerial++;
}
string joinedSerialsList = string.Format("({0})", string.Join(", ", serialsList));
OleDbConnection connection = BadgeDatabaseDB.GetConnection();
string checkStatement
= "SELECT SerialNumber, OrderNumber "
+ "FROM SerialNumbersMFG "
+ "WHERE SerialNumber IN (#List)";
OleDbCommand command = new OleDbCommand(checkStatement, connection);
command.Parameters.AddWithValue("#List", joinedSerialsList);
string duplicateSerials = "";
try
{
connection.Open();
OleDbDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
duplicateSerials += dataReader["OrderNumber"].ToString() + "\n";
}
}
catch (OleDbException ex)
{
throw ex;
}
finally
{
connection.Close();
}
return duplicateSerials;

I rewrited your sample, this work:
private IEnumerable<string> getData()
{
// Create comma delimited list of serials:
int currentSerial = 4452; // your constant
var serialsList = new List<int>();
var count = 100;
for (int i = 0; i < count; i++)
serialsList.Add(currentSerial++);
var connString = getConnectionString();
var results = new List<string>();
string sqlSelect = $"SELECT SerialNumber, OrderNumber FROM SerialNumbersMFG WHERE SerialNumber IN ({string.Join(",", serialsList)})";
using (var connection = new SqlConnection(connString)) // BadgeDatabaseDB.GetConnection();
{
using (var command = new SqlCommand(sqlSelect, connection))
{
connection.Open();
var dataReader = command.ExecuteReader();
while (dataReader.Read())
results.Add(dataReader["OrderNumber"].ToString());
}
}
return results;
}

Related

C# 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException'

Have the error 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException, however VisualStudio does not pause the program and throw the exception at me. Here is the code:private void BTN_NA_Click(object sender, EventArgs e)
{
if (TXT_NAUN.Text != "" && TXT_NAPW.Text != "" && TXT_NAPW2.Text != "")
{
if (TXT_NAPW.Text == TXT_NAPW2.Text)
{
string input = TXT_NAPW.Text;
int hash = 0;
int output = 0;
foreach (char chara in input)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
output = output + temp;
output = output * 2;
}
hash = output % 1000;
OleDbConnection dbConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BHShooterProjectDB.accdb");
string sql = "SELECT Accounts.PlayerID FROM Accounts ORDER BY Accounts.PlayerID DESC ";
///string comm = "SELECT Accounts.PlayerID from Accounts";
/// INNER JOIN Leaderboard ON Leaderboard.PlayerID = Accounts.PlayerID WHERE Accounts.PlayerUsername = #ip";
OleDbCommand cmd = new OleDbCommand(sql, dbConn);
string result = "";
dbConn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
result = reader[0].ToString();
}
dbConn.Close();
{
string comm = "INSERT INTO Accounts (PlayerUsername, PlayerPassword, PlayerID, PlayerInvID) VALUES (#NAUN, #HPW, #NAPI, #NAPI)";
OleDbCommand command = new OleDbCommand(comm, dbConn);
command.Parameters.AddWithValue("#NAUN", TXT_NAUN.Text);
command.Parameters.AddWithValue("#HPW", hash);
foreach (char chara in result)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
result = result + temp;
}
result = result + 1;
command.Parameters.AddWithValue("#NAPI", result);
command.Parameters.AddWithValue("#NAPI", result);
dbConn.Open();
int rowsAffected = cmd.ExecuteNonQuery(); ///error appears here
dbConn.Close();
}
}
}
}
Any suggestions on solution, have tried a lot and this is my last hope!
Thanks,
Blackclaw_
At the line you got the error, you are using cmd (the select command). I think you want to use command (the insert command).

Copy multiple column values from SqlReader to array?

How can I generate an array of string that will contain all the column info.
this query will return a single row with multiple columns
var rowLines = new List<string>();
try
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
string query = "SELECT I1,I2,I3,I4,I5,I6,I7,I8,I9,I10,I11,I12,I13,I14,I15 FROM LABEL_OUT WHERE LABEL_NAME='" + labelName + "'";
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
rowLines.Add(reader[0].ToString());
}
}
}
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
here rowLines will Contain all the column value such as I1,I2,.....I15
Probably the easiest way to do this is to use DbDataReader.GetValues(object[]), which populates a pre-existing array with the values from each column:
var vals = new object[reader.FieldCount];
while (reader.Read())
{
reader.GetValues(vals);
// ... do something with the values
}
If you are sure that you will take a single line you could loop on the reader using the FieldCount and add each element on a List<string>. Finally, you could just return it as an array.
var rowLines = new List<string>();
if (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
rowLines.Add(reader.IsDBNull(i) ? string.Empty : reader[i].ToString());
}
}
return rowLines.ToArray();

Add string array to SQL query

I have a string array which consists of identifiers. I want to get some values from SQL using these identifiers . Is there a way of adding them with a string value to SqlCommand parameters?
I want to create a query like:
select CaseList from MasterReportData where Id = 1 OR Id = 2 OR Id = 3
This is my C# code:
public static List<string> GetCaseList(string[] masterIdList)
{
try
{
string query = " select CaseList from MasterReportData where #masterId";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
conn.Close();
}
catch (Exception e)
{
var err= 0;
}
return list;
}
There are many different ways you can go about doing this but I prefer to create a temp table of possible values. That way you can do something like
select CaseList from MasterReportData where Id IN(select Id from tempTable)
The best approach (with sql optimization) would be:
Create your Type:
CREATE TYPE dbo.IntTTV AS TABLE
( Id int )
Your Ids:
var ids = new List<int>
{
1,
2,
3,
}
Create a schema:
var tableSchema = new List<SqlMetaData>(1)
{
new SqlMetaData("Id", SqlDbType.Int) // I think it's Int
}.ToArray();
Create the table in C#
var table = ids
.Select(i =>
{
var row = new SqlDataRecord(tableSchema);
row.SetInt32(0, i);
return row;
})
.ToList();
Create the SQL Parameter
var parameter = new SqlParameter();
parameter.SqlDbType = SqlDbType.Structured;
parameter.ParameterName = "#Ids";
parameter.Value = table;
parameter.TypeName = "dbo.IntTTV";
var parameters = new SqlParameter[1]
{
parameter
};
Slightly change your query (this is just an example:)
string query = "select mrd.CaseList from MasterReportData mrd"
+ " inner join #ids i on mrd.Id = i.id";
public static List<string> GetCaseList(string[] masterIdList)
{
List<string> list = new List<string>();
try
{
string query = "select CaseList from MasterReportData where ";
using (SqlConnection conn = new SqlConnection(connString))
{
int i = 0;
SqlCommand cmd = new SqlCommand(query, conn);
for(i = 0; i < masterIdList.Length; i++)
{
var parm = "#ID" + i;
cmd.Parameters.Add(new SqlParameter(parm, masterIdList[i]));
query += (i > 0 ? " OR " : "") + " Id = " + parm;
}
cmd.CommandText = query;
//cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
}
}
catch (Exception e)
{
e.ToString();
}
return list;
}

Is my logic correct? I'm trying to calculate the total amount of each loop that's being read in a foreach loop?

So I grab each row in a foreach loop and calculate the price of it. I managed to do that but I can't seems to figure out how to store ALL the calculated rows into a single variable and insert 1 calculated answer into a database.
private void btnSubmitConsultation_Click(object sender, EventArgs e)
{
string cMedication = string.Empty;
string cQuantity = string.Empty;
string cAppointment = string.Empty;
foreach (DataGridViewRow row in this.dataPrescription.Rows)
{
cMedication = row.Cells[0].Value.ToString();
cQuantity = row.Cells[1].Value.ToString();
cAppointment = txtAppointmentID.Text;
if (cAppointment == "NO APPOINTMENT HAS BEEN MADE")
{
MessageBox.Show("Please make an appointment first at the Nurse counter", "WARNING");
}
else
{
this.calculateTotal(cMedication, cQuantity, cAppointment);
}
}
}
private void calculateTotal(string cMedication, string cQuantity, string cAppointment)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnectionString);
string insertPayment = "INSERT INTO PAYMENT (amount, appointmentID) " +
"VALUES (#insertAmount, #insertAppointment)";
using (SqlConnection connection = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdPayment = new SqlCommand(insertPayment, connection))
{
string strPrice = "SELECT medicationPrice FROM MEDICATION WHERE medicationName= #getName";
SqlCommand cmdPrice = new SqlCommand(strPrice, con);
cmdPrice.Parameters.AddWithValue("#getName", cMedication);
con.Open();
SqlDataReader readPrice = cmdPrice.ExecuteReader();
if (readPrice.Read())
{
string getPrice = readPrice["medicationPrice"].ToString();
double doublePrice = Convert.ToDouble(getPrice);
double doubleQuantity = Convert.ToDouble(cQuantity);
double result = doublePrice * doubleQuantity;
for (int i = 0; i < dataPrescription.Rows.Count; i++)
{
double total = result * i;
string answer = result.ToString();
MessageBox.Show(answer);
cmdPayment.Parameters.AddWithValue("#insertAmount", answer);
}
}
readPrice.Close();
con.Close();
cmdPayment.Parameters.AddWithValue("#insertAppointment", txtAppointmentID.Text);
connection.Open();
cmdPayment.ExecuteNonQuery();
connection.Close();
}
}
}
You have to change the command text to be the insert statement.
connection.Open();
cmdPayment.CommandText = insertPayment;
cmdPayment.ExexuteNonQuerry();

select all from access and place in string

I'm having trouble selecting all items from my access database. I want to select the data in the entire row and keep it in a string, separating each item by a ";". Below is the code i have that will give me the column i specify, but i want all the data in the row.
con.Open();
type= checkBox49.Text;
String str = "Select * from distro where type='" + type + "'";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
str2 = dr.GetString(1);
}
You can try something like this where columnsCount is the number of your columns in your database table
if (dr.Read())
{
for (int i = 0; i <columnsCount; i++)
{
str2 += string.Join(";",sdr.GetString(i));
}
}
You could select each field by name and combine them together like
str2 = dr["FieldName"].ToString() + "." + dr["FieldName"].ToString();
Also, I wouldn't reference any fields by number, but by FieldName.
So one approach, with the current code, would be this:
StringBuilder sb = new StringBuilder();
if (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
if (sb.Length > 0) { sb.Append(";"); }
sb.Append(dr.GetString(i));
}
}
A more global code if all your columns are not string type :
var con = new OleDbConnection();
var cmd = new OleDbCommand(str, con);
var dr = cmd.ExecuteReader();
var res = string.Empty;
if (dr.Read())
{
object[] t = new Object[dr.FieldCount];
if (dr.GetValues(t)>0)
{
res = String.Join(";", (from el in t select el as string).Where(x => x!=null).ToArray());
}
}
return res;
You could just string.Join all the values together.
con.Open();
type = checkBox49.Text;
String str = "Select * from distro where type=?";
cmd = new OleDbCommand(str, con);
cmd.Parameters.Add(type);
using (dr = cmd.ExecuteReader())
{
if (dr.Read())
{
var values = new object[dr.FieldCount];
dr.GetValues(values);
str2 = string.Join(";", values.Skip(1).Select(d => d.ToString());
}
}
Notice the use of a parameter in the query too. Standard way to avoid SQL Injection.

Categories

Resources