How to get more values from Access c# - c#

I want to select a sentence from the database, but i don't know how to write the code. I will search for a number by reading lines from the textbox.
for (int i = 0; i < lines.GetUpperBound(0); i++)
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query1 = "SELECT TOP 1 * FROM SolozinnenTabel WHERE Faciliteitnummer = " + lines[i] + " AND Paragraaf LIKE '" + AlineaKinderenNaam + "%' ORDER BY rnd(ID)";
command.CommandText = query1;
OleDbDataReader reader1 = command.ExecuteReader();
while (reader1.Read()) {
RichAccoText.Text = RichAccoText.Text + reader1["Zin"].ToString();
RichFacilityText.Lines = RichFacilityText.Lines.Where(line => line != lines[i]).ToArray();
}
}
This code works but I only can search for one line and search them in the textbox. So I want something like this:
string query1 = "SELECT TOP 1 * FROM CombizinnenTabel WHERE (Faciliteitnummer1= " + lines[a] + " AND Faciliteitnummer2= " + lines[a] + ") AND Paragraaf LIKE '" + AlineaAccommodatieNaam + "%' ORDER BY rnd(ID)";
lines[a] = 80, but I want to search:
If Faciliteitnummer1 = lines[80] en Faciliteitnummer2 = lines[48]and Faciliteitnummer3 = lines[18], then select this sentence.....
If (Faciliteitnummer1 = lines[80] en Faciliteitnummer2 = lines[10]and Faciliteitnummer3 = lines[0], then select this sentence....

Related

Variable in C# SQL query not working

I have a loop in which I grab certain ID's to make a call in a database. There are 2 variables within the query.
The first one works fine but the second one returns nothing. I have tested it a lot and know that the correct value is coming through to the query. Not sure what I am doing wrong here. I replace the variable with a hard coded value that I know is returning and it works fine.
Here is my code:
SqlDataAdapter d8;
d8 = new SqlDataAdapter("SELECT SUM(CAST(AMOUNT AS BIGINT)) AS NEW_AMOUNT
FROM ddb_proc_log_base
WHERE (PROVID = " + docId +
" AND CHART_STATUS = 90
AND YEAR(PLDATE) = 2016
AND CLASS = 2
AND ORD = " + defer + ") OR (ORD = " + defer +
" AND PROVID = " + this.getDocHygDS.Tables[0].Rows[t]["HYG_ID"] +
" AND CHART_STATUS = 90
AND YEAR(PLDATE) = 2016 AND CLASS = 2)", conn3);
cmdBuilder5 = new SqlCommandBuilder(d8);
d8.Fill(this.balances);
#Tyler Nichol You are missing the a single quote where you concatenate string value like
Example ORD = '" + defer + "'
below is an example:
try{
"select * from SomeTable where name='"+name+","
// in your case this may like the following
d8 = new SqlDataAdapter("select SUM(CAST(AMOUNT AS BIGINT)) AS NEW_AMOUNT
FROM ddb_proc_log_base where ( PROVID = "+docId+" AND CHART_STATUS = 90
AND YEAR(PLDATE) = 2016 AND CLASS = 2 AND ORD = '" + defer + "') OR (ORD = '"
+ defer + "' AND PROVID = " + this.getDocHygDS.Tables[0].Rows[t]["HYG_ID"]
+ " AND CHART_STATUS = 90 AND YEAR(PLDATE) = 2016 AND CLASS = 2)", conn3);
}
catch(Exception e)
{
//Throw Null Exception Here
}
Recommended Solution
try{
string UserName="John";
cmd.CommandText = "select * from SomeTable where name=#Name";
cmd.Parameters.AddWithValue("#Name", UserName);
}
catch(Exception e)
{
//Throw Null Exception Here
}
You need to use a CONTAIN in the query :
DataSet getDocHygDS = new DataSet();
string[] hyg_id = getDocHygDS.Tables[0].AsEnumerable().Select(x => x.Field<string>("HYG_ID")).Distinct().ToArray();
string or = "'" + string.Join("' OR '", hyg_id) + "'";
SqlDataAdapter d8;
string query = string.Format("SELECT SUM(CAST(AMOUNT AS BIGINT)) AS NEW_AMOUNT" +
" FROM ddb_proc_log_base" +
" WHERE (PROVID = {0}" +
" AND CHART_STATUS = 90" +
" AND YEAR(PLDATE) = 2016" +
" AND CLASS = 2" +
" AND ORD = {1})" +
" OR" +
" (ORD = {1}" +
" AND CONTAINS(PROVID, {2})" +
" AND CHART_STATUS = 90" +
" AND YEAR(PLDATE) = 2016 AND CLASS = 2)", docId, defer, or);
d8 = new SqlDataAdapter(query, conn3);
cmdBuilder5 = new SqlCommandBuilder(d8);
d8.Fill(this.balances);

C# SQLite database locked

I've tried all the solutions I could find to this problem, but for some reason I still get an exception stating the database I'm using is locked.
My code is as follows:
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
using (SQLiteConnection OriginatorDBConnection = new SQLiteConnection(connectionString))
{
string originatorName, originatorOrganisation, originatorAddress, originatorCellNumber, originatorTelNumber, originatorEmail;
originatorName = originatorNameTextBox.Text;
originatorOrganisation = originatorOrganisationTextBox.Text;
originatorAddress = originatorAddressRichTextBox.Text;
originatorCellNumber = originatorCellTextBox.Text;
originatorTelNumber = originatorTelTextBox.Text;
originatorEmail = originatorEmailTextBox.Text;
OriginatorDBConnection.Open();
string originatorINSERT = "INSERT INTO Originator (Name, Organisation, Address, CellphoneNumber, TelephoneNumber, Email) VALUES ('" + originatorName + "', '" + originatorOrganisation + "', '" + originatorAddress + "', '" + originatorCellNumber + "', '" + originatorTelNumber + "', '" + originatorEmail + "');";
using (SQLiteCommand originatorCommand = new SQLiteCommand(originatorINSERT, OriginatorDBConnection))
{
originatorCommand.ExecuteNonQuery();
}
OriginatorDBConnection.Close();
}
The closest solution on here that I could find to the problem was here: SQLite Database Locked exception
It didn't seem to work on my problem, however.
What am I doing wrong?
I have an additional function wherein I use the connection:
public AdminForm()
{
//Initialise AdminForm components.
InitializeComponent();
//Establish and open connection to ObservationDB.
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
ObservationDBConnection = new SQLiteConnection(connectionString);
ObservationDBConnection.Open();
//Query database to find all originators
string originatorSELECT = "SELECT * FROM Originator;";
string ECPNumberSELECT = "SELECT * FROM ECP";
SQLiteCommand command = new SQLiteCommand(originatorSELECT, ObservationDBConnection);
SQLiteDataReader reader = command.ExecuteReader();
SQLiteCommand command2 = new SQLiteCommand(ECPNumberSELECT, ObservationDBConnection);
SQLiteDataReader reader2 = command2.ExecuteReader();
//Populate OriginatorName combobox with names of existing originators.
List<string> originatorNames = new List<string>();
while (reader.Read())
{
originatorNames.Add(Convert.ToString(reader["Name"]));
}
OriginatorNameComboBox.DataSource = originatorNames;
//Populate ECP combobox with numbers of existing ECP.
List<string> ECPNumbers = new List<string>();
while (reader2.Read())
{
ECPNumbers.Add(Convert.ToString(reader2["Number"]));
}
ECPNumComboBox.DataSource = ECPNumbers;
//Populate TC Decision combobox with options.
List<string> TCDecision = new List<string>();
TCDecision.Add("Rework");
TCDecision.Add("Reject");
TCDecision.Add("Approve");
TCDecisionComboBox.DataSource = TCDecision;
ObservationDBConnection.Close();
}
And here:
private void SaveButton_Click(object sender, EventArgs e)
{
ObservationDBConnection.Open();
...
string ImpactTypeINSERT = "INSERT INTO ImpactType (ImpactType, Description) VALUES ('" + impactType + "', '" + impactDescription + "');";
SQLiteCommand ImpactTypeCommand = new SQLiteCommand(ImpactTypeINSERT, ObservationDBConnection);
//SQLiteDataReader ImpactTypeReader = ImpactTypeCommand.ExecuteReader();
ImpactTypeCommand.ExecuteNonQuery();
...
string TCDecisionINSERT = "INSERT INTO TCDecision (Decision, Description) VALUES ('" + TechnicalCommitteeDecision + "', '" + TechnicalCommitteeDescription + "');";
SQLiteCommand TCDecisionCommand = new SQLiteCommand(TCDecisionINSERT, ObservationDBConnection);
SQLiteDataReader TCDecisionReader = ImpactTypeCommand.ExecuteReader();
TCDecisionCommand.ExecuteNonQuery();
...
string OperationalDecisionINSERT = "INSERT INTO OperationalDecision (Decision, Description) VALUES ('" + operationalDecision + "', '" + operationalDescription + "');";
SQLiteCommand OperationalDecisionCommand = new SQLiteCommand(OperationalDecisionINSERT, ObservationDBConnection);
//SQLiteDataReader OperationalDecisionReader = OperationalDecisionCommand.ExecuteReader();
OperationalDecisionCommand.ExecuteNonQuery();
...
...
string OriginatorIDSELECT = "SELECT * FROM Originator WHERE Name='" + OriginatorNameComboBox.Text + "';";
SQLiteCommand OriginatorIDCommand = new SQLiteCommand(OriginatorIDSELECT, ObservationDBConnection);
SQLiteDataReader OriginatorIDReader = OriginatorIDCommand.ExecuteReader();
originatorIDOBS = OriginatorIDReader.GetOrdinal("ID");
//ImpactType
string impactTypeSELECT = "SELECT * FROM ImpactType WHERE ImpactType='" + impactType + "';";
SQLiteCommand impactTypeOBSCommand = new SQLiteCommand(impactTypeSELECT, ObservationDBConnection);
SQLiteDataReader impactTypeOBSReader = impactTypeOBSCommand.ExecuteReader();
impactTypeOBS = impactTypeOBSReader.GetOrdinal("ID");
string operationalDecisionOBSSELECT = "SELECT * FROM OperationalDecision WHERE Decision='" + operationalDecision + "';";
SQLiteCommand operationalDecisionOBSCommand = new SQLiteCommand(operationalDecisionOBSSELECT, ObservationDBConnection);
SQLiteDataReader operationalDecisionOBSReader = operationalDecisionOBSCommand.ExecuteReader();
operationalDecisionOBS = operationalDecisionOBSReader.GetOrdinal("ID");
...
string ECPOBSSELECT = "SELECT * FROM ECP WHERE Number='" + ECPNumComboBox.Text + "';";
SQLiteCommand ECPCommand = new SQLiteCommand(ECPOBSSELECT, ObservationDBConnection);
SQLiteDataReader ECPReader = ECPCommand.ExecuteReader();
ECPOBS = ECPReader.GetOrdinal("ID");
string CNISObservationINSERT = "INSERT INTO CNISObservation (Title, ReceiveDate, TableDate, OriginatorID, OriginatorReference, OriginatorDate, ObservationNumber, RevisionNumber, Description, Status, ImpactDescription, ImpactType, OperationalRequirementDescription, OperationalImpact, OperationalDecision, ProposedAction, TCDecision, ECP, SolutionOperationalImpact, TechnicalSolutionImpact) VALUES ('" +
titleOBS + "','"
+ receiveDateOBS + "','"
+ tableDateOBS + "','"
+ originatorIDOBS + ",'"
+ originatorReferenceOBS +"','"
+ originatorDateOBS + "','"
+ observationNumberOBS + "',"
+ revisionNumberOBS + ",'"
+ descriptionOBS + "',"
+ statusOBS + ",'"
+ impactDescriptionOBS + "',"
+ impactTypeOBS + ",'"
+ operationalRequirementDescriptionOBS + "','"
+ operationalImpactOBS + "',"
+ operationalDecisionOBS + ",'"
+ TCDecisionOBS + ","
+ ECPOBS + ",'"
+ solutionOperationalImpactOBS + "','"
+ technicalSolutionImpactOBS + "');";
...
string obsOBSSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationIDCommand = new SQLiteCommand(obsOBSSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationIDReader = CNISObservationIDCommand.ExecuteReader();
observationID = CNISObservationIDReader.GetOrdinal("ID");
...
foreach (var capabilityID in capabilitiesSelected)
{
string ObservationOperationalCapabilitiesINSERT = "INSERT INTO ObservationOperationalCapabilities (CapabilityID, ObservationID) VALUES (" + capabilityID + "," + observationID + ");";
SQLiteCommand ObservationOperationalCapabilitiesCommand = new SQLiteCommand(ObservationOperationalCapabilitiesINSERT, ObservationDBConnection);
// SQLiteDataReader ObservationOperationalCapabilitiesReader = ObservationOperationalCapabilitiesCommand.ExecuteReader();
ObservationOperationalCapabilitiesCommand.ExecuteNonQuery();
}
...
string CNISObservationIDSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationCommand = new SQLiteCommand(CNISObservationIDSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationReader = CNISObservationCommand.ExecuteReader();
CNISObservationID = CNISObservationReader.GetOrdinal("ID");
string CNISReleaseINSERT = "INSERT INTO CNISSection VALUES (" + CNISObservationID + "," + CNISRelease + "," + chapter + ",'" + paragraph + "','" + section + "','" + page +"');";
SQLiteCommand CNISReleaseCommand = new SQLiteCommand(CNISReleaseINSERT, ObservationDBConnection);
//SQLiteDataReader CNISReleaseReader = CNISReleaseCommand.ExecuteReader();
CNISReleaseCommand.ExecuteNonQuery();
ObservationDBConnection.Close();
}
I know I'm a lot late to the game, but it looks like you're not closing you reader variables in AdminForm() constructor. Consider wrapping the DataReaders in a using().
Wrapping around Command and Reader did work for me:
using (SqliteCommand cmd = new SqliteCommand(sQuery, m_Conn))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
ret_type = reader.GetInt32(0);
}
}
}
Please be aware to click on Write changes on SQLite browser if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post request worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception

Multiple OleDbCommands producing System Resource Exceeded

So basically I have a C# project, that iterates through every student (300 students) within a table called Student within a Microsoft Access 2016 database. In a single iteration for a single student by using other tables like Mathematics, Reading that have a 1-to-1 relationship with the Student table, to grab the data that belongs to that student.
try
{
OleDbCommand allStudents = new OleDbCommand("SELECT [NSN]"
+ " FROM [Student]; ");
allStudents.Connection = conn;
OleDbDataAdapter allData = new OleDbDataAdapter(allStudents);
DataTable allTable = new DataTable();
allData.Fill(allTable);
foreach (DataRow dr in allTable.Rows)
{
string NSN = dr["NSN"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * "
+ "FROM (((([Student] s "
+ "INNER JOIN [Student Extra] se ON se.[NSN] = s.[NSN]) "
+ "INNER JOIN [Reading] r ON r.[NSN] = s.[NSN])"
+ "INNER JOIN [Writing] w ON w.[NSN] = s.[NSN])"
+ "INNER JOIN [Mathematics] m ON m.[NSN] = s.[NSN]) "
+ "WHERE s.[NSN] = '" + NSN + "'; ");
cmd.Connection = conn;
OleDbDataAdapter daa = new OleDbDataAdapter(cmd);
DataTable dtt = new DataTable();
daa.Fill(dtt);
foreach (DataRow drr in dtt.Rows)
{
firstName = drr["Preferred Name"].ToString();
gender = drr["Gender"].ToString();
room = drr["Room Number"].ToString();
NSAchieve = drr["National Standard Achieve"].ToString();
NSProgress = drr["National Standard Progress"].ToString();
The above code is only a snippet of the code I have, but this is basically where the function will start.
By using this data, I want to be able to go through several SELECT statements for other tables and compare them and produce a calculated value.
Dictionary<string, OleDbCommand> d = new Dictionary<string, OleDbCommand>();
cmd = new OleDbCommand("SELECT [Achievement Statement]"
+ " FROM [National Standard Codes]"
+ " WHERE [National Standard Code] = '" + readingNSAchievementCode + "'; ");
d["readingNSAchievementOTJ"] = cmd;
cmd = new OleDbCommand("SELECT [" + NSAchieve + "]"
+ " FROM [Reading National Standards]"
+ " WHERE [Assessment] = '" + readingFinalAssessment + "'; ");
d["readingNSAchievementComp"] = cmd;
cmd = new OleDbCommand("SELECT [Timeframe]"
+ " FROM [Reading Statements]"
+ " WHERE [Year Code] = '" + NSProgress + "'; ");
d["readingNSProgressTimeframe"] = cmd;
There are several more commands, (approx <150). I use a Dictionary to store my Commands, and then execute the commands in a FOREACH loop.
foreach(KeyValuePair<string, OleDbCommand> pair in d)
{
try
{
string v = pair.Key;
OleDbCommand dbCmd = pair.Value;
dbCmd.Connection = conn;
OleDbDataReader reader = dbCmd.ExecuteReader();
reader.Read();
readingDict[v] = reader.GetString(0);
}
catch (Exception e)
{
MessageBox.Show("Error at " + pair.Key + "\n\n Here is message " + e);
}
}
After executing and getting my value, I want to store my data into another table called Calculated.
string insert1 = "INSERT INTO [Calculated] (";
int i = 0;
Dictionary<string, string> dict = createDictionary(NSN);
int len = dict.Count / 2;
foreach (KeyValuePair<string, string> pair in dict)
{
string field = pair.Key;
string value = pair.Value;
if (i == (len - 1))
{
insert1 += "[" + field + "])";
break;
}
else
{
insert1 += "[" + field + "], ";
}
i++;
}
insert1 += " VALUES (";
i = 0;
foreach (KeyValuePair<string, string> pair in dict)
{
string field = pair.Key;
string value = pair.Value;
if (i == len - 1)
{
insert1 += "'" + value + "')";
break;
}
else
{
insert1 += "'" + value + "', ";
}
i++;
}
I build my INSERT INTO query, and then I execute using an OleDbCommand. This needs to repeat 300 times, but for development purposes currently I only have 5 students in my Student table. However when executing after the 4th student it will always consistently give me an error System Resources Exceeded always at a specific OleDbCommand. I have tested each command separately, so there is no issue with the way the OleDbCommands are written.
I have tried searching on here, and tried to encase the first code snippet in a using statement, using using (OleDbConnection conn = new OleDbConnection(connectionStr)) but as I am still a novice at C#, I am unable to produce a solution.

OleDbDataReader returns empty value

I have a couple of days to come up with a solution to my problem and I can not. When running the following code:
OleDbConnection MyconnectionBDD = null;
MyconnectionBDD = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + bdd.Text);
//MyconnectionBDD = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + bdd.Text);
MyconnectionBDD.Open();
OleDbCommand cmdBDD = MyconnectionBDD.CreateCommand();
OleDbDataReader dbReaderBDD = null;
string queryBDD;
queryBDD = "SELECT MAX(Clientes.Codigo) AS CodEmp FROM Clientes WHERE Clientes.Codigo LIKE '" + int.Parse(dbReaderExcel.GetValue(0).ToString().Substring(3, 2)) + "*'";
//queryBDD = "SELECT MAX(Clientes.Codigo) FROM Clientes WHERE Codigo LIKE '17*'";
cmdBDD.CommandText = queryBDD;
cmdBDD.CommandType = CommandType.Text;
dbReaderBDD = cmdBDD.ExecuteReader();
if (dbReaderBDD.HasRows)
{
dbReaderBDD.Read();
//string codEmp = dbReaderBDD.GetString(0); //GetValue(0).ToString();
MessageBox.Show(dbReaderBDD["CodEmp"].ToString());
MessageBox.Show(dbReaderBDD.GetValue(0).ToString()); //GetInt64(0).ToString());
//if (dbReaderBDD.GetValue(0).ToString() != "")
if (!String.IsNullOrEmpty(dbReaderBDD.GetValue(0).ToString()))
if (dbReaderBDD.GetValue(0).ToString().Length == 6)
last_codigoCli = int.Parse(dbReaderBDD.GetValue(0).ToString().Substring(1, 5));
else
last_codigoCli = int.Parse(dbReaderBDD.GetValue(0).ToString().Substring(2, 5));
last_codigoCli_Revisado = last_codigoCli;
}
dbReaderBDD.Close();
It returned an empty value, but if I run the query in Access it return a correct value:
SELECT MAX(Clientes.Codigo) AS CodEmp FROM Clientes WHERE Clientes.Codigo LIKE '17*'
Please can someone help me? Thanks
Sorry, the query would be:
queryBDD = "SELECT MAX(Clientes.Codigo) AS CodEmp FROM Clientes WHERE Clientes.Codigo LIKE '" + int.Parse(dbReaderExcel.GetValue(0).ToString().Substring(3, 2)) + "%'";
As the * is the wildcard in Access, I thought that the query had to put a * but was %
Thanks

Parameters supplied for object which is not a function. If the parameters are intended as a table hint, a WITH keyword is required

I'm running Windows 7 and II7 and SQL server 2008 R2 . I have an aspx program and when I try to run it I get the following error
Parameters supplied for object 'users' which is not a function. If
the parameters are intended as a table hint, a WITH keyword is
required.
What I've coded is this :
public ArrayList GetGoodsList(string type, string goodsType, string user, string payType, bool flag)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Conn"].ToString());
DataSet ds = new DataSet();
sSql = "select count(*) from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sSql;
conn.Open();
int maxRow = Int32.Parse(cmd.ExecuteScalar().ToString());
sSql = "select * from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
cmd.CommandText = sSql;
SqlDataReader reader = cmd.ExecuteReader();
ArrayList gInfos = new ArrayList();
GoodsInfo gInfo;
for (int i = 0; i < maxRow; i++)
{
if (reader.Read())
{
gInfo = new GoodsInfo();
gInfo.G_ID = Int32.Parse(reader["G_ID"].ToString());
gInfo.G_Name = reader["G_Name"].ToString();
gInfo.Type = reader["Type"].ToString();
gInfo.GoodsType = reader["GoodsType"].ToString();
gInfos.Add(gInfo);
}
}
conn.Close();
return gInfos;
}
Any idea? Thanks!
Without giving away the answer, your issue in in your SELECT statement, sSql = ...
It's not the correct SQL syntax.
Have a read of this wikipedia article on the SELECT statement.

Categories

Resources