SELECT COUNT query not producing the result I'm expecting - c#

I have a SELECT COUNT query that is used to determine whether the user has already been given a grade or not and if that particular user has a grade already the button to submit a grade will become invisible. However, the button still appears even though I've given that student a grade. When I launch in debugging mode the value of the query is null. Below is the code in the method:
String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
String modOnpwayModID = "SELECT id FROM module_on_pathway WHERE module_id = '" + modDropDown.SelectedValue + "'";
SqlCommand modOnpwayModIDQuerycmd = new SqlCommand(modOnpwayModID, myConnection);
Int32 modOnpwayModIDResult = Convert.ToInt32(modOnpwayModIDQuerycmd.ExecuteScalar().ToString());
Label lb = (Label)e.Item.FindControl("user_idLabel");
String userIDLabel = lb.Text.ToString();
Int32 usrIDVal = Convert.ToInt32(userIDLabel);
String gradeSelectionQuery = "SELECT COUNT(student_module_grade.grade) FROM student_module_grade INNER JOIN classlist ON student_module_grade.classlist_id = classlist.classlist_id INNER JOIN student_assignment_grade ON student_module_grade.classlist_id = student_assignment_grade.classlist_id INNER JOIN assignments ON student_assignment_grade.assignment_id = assignments.assignment_id WHERE student_module_grade.module_on_pathway_id ='" + modOnpwayModIDResult + "'AND classlist.user_id = '" + userIDLabel + "'";
SqlCommand gradeSelectionQuerycmd = new SqlCommand(gradeSelectionQuery, myConnection);
Int32 gradeCount = Convert.ToInt32(gradeSelectionQuerycmd.ExecuteScalar().ToString());
//See if a final score has been given already- can then be changed by the admin if it needs to be changed
if (gradeCount == 0)
{
submitmodMark1st.Visible = true;
//All elements for grade submission made invisible- admin will be unable to change the grade
//TB.Visible = false;
//changedFlagVal.Text = "The grade for this module has already been changed for the selected student";
//changedFlagVal.Visible = true;
//changedFlagVal.ForeColor = System.Drawing.Color.Red;
}
else
{
submitmodMark1st.Visible = false;
}
String repeatGradeSelectionQuery = "SELECT COUNT(student_module_repeat_grades.grade) FROM student_module_repeat_grades INNER JOIN classlist ON student_module_repeat_grades.classlist_id = classlist.classlist_id INNER JOIN student_assignment_grade ON student_module_repeat_grades.classlist_id = student_assignment_grade.classlist_id INNER JOIN assignments ON student_assignment_grade.assignment_id = assignments.assignment_id WHERE student_module_repeat_grades.module_on_pathway_id ='" + modOnpwayModIDResult + "'AND classlist.user_id = '" + userIDLabel + "'";
SqlCommand repeatGradeSelectionQuerycmd = new SqlCommand(repeatGradeSelectionQuery, myConnection);
Int32 repeatGradeCount = Convert.ToInt32(repeatGradeSelectionQuerycmd.ExecuteScalar().ToString());
if (repeatGradeCount == 0)
{
submitmodMark1st.Visible = true;
}
else
{
//All elements for grade submission made invisible- admin will be unable to change the grade
//TB.Visible = false;
changedFlagVal.Text = "The grade for this module has already been changed for the selected student";
changedFlagVal.Visible = true;
changedFlagVal.ForeColor = System.Drawing.Color.Red;
submitmodMark1st.Visible = false;
}

You could convert that into a stored procedure like this in your SQL-
CREATE PROC getCountStudentModule #pathwayId int, #userID int
AS
BEGIN
SELECT COUNT(student_module_repeat_grades.grade) AS CntRepeatGrades
FROM student_module_repeat_grades
INNER JOIN classlist
ON student_module_repeat_grades.classlist_id = classlist.classlist_id
INNER JOIN student_assignment_grade
ON student_module_repeat_grades.classlist_id = student_assignment_grade.classlist_id
INNER JOIN assignments
ON student_assignment_grade.assignment_id = assignments.assignment_id
WHERE student_module_repeat_grades.module_on_pathway_id = #pathwayId
AND classlist.user_id = #userID
END
GO
And then do something like this-
public bool CheckStatus()
{
bool status = false;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("getCountStudentModule", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pathwayid", modOnpwayModIDResult);
cmd.Parameters.AddWithValue("#userID", userIDLabel);
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
string active = rdr["CntRepeatGrades"].ToString();
if (active == "0")
{
status = true;
}
else
{
status = false;
}
}
}
return status;
}
}
And then you can do a check like this for your button-
bool status = CheckStatus();
if (status)
{
submitmodMark1st.Visible = true;
}
else
{
//All elements for grade submission made invisible- admin will be unable to change the grade
//TB.Visible = false;
changedFlagVal.Text = "The grade for this module has already been changed for the selected student";
changedFlagVal.Visible = true;
changedFlagVal.ForeColor = System.Drawing.Color.Red;
submitmodMark1st.Visible = false;
}

Related

How to check if user in mysql database exists (in c#)

So I know this is a often asked question but I want to check if the username is already taken in the database using c#. I tried this:
MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM tablename WHERE(name = '" + tb1.Text + "');");
cmd2.Connection = connect;
connect.Open();
string unt = "";
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
unt= dr.GetString("name");
}
dr.Close();
}
catch (Exception ex)
{
errorbox.Content = ex.Message;
}
finally
{
connect.Close();
}
if(unt == "" || unt == "0") {
continuel = false;
tb2.Text = "User " +tb1.Text+ " doesn't exist!";
Popup1.IsOpen = true;
}
Its a WPF project and the variable 'continuel' is set to true by default. The code doesn't recognize if a user doesn't exist.
First off your code is vulnerable to sql inject, you should never concatenate values into a query. secondly you can do a count and execute a scalar. Not I stripped down your code a little you'll have to add error handling back.
bool userExists = false;
private String sql = "SELECT COUNT(*) FROM tableName WHERE name = #usernameparam;";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.AddWithValue("#usernameparam", tb1.Text.Trim());
int userCount = Convert.ToInt32(m.ExecuteScalar());
if(userCount>0)
{
userExists = true;
}
//use userExists variable to evaluate if user exists

c# Using Two MysqlReaders

I want to retrive data from two differentables in my mysql data base so i created one connection and two readers, The second reader is not returning any results but the first reader is.
public List<BlogContentItemClass> BCITLIST = new List<BlogContentItemClass>();
// GET: api/BlogContents
[HttpGet]
public List<BlogContentItemClass> Get(string id)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `id` = '" + id + "' ";
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
BlogContentItemClass BCIT = new BlogContentItemClass();
Label BLOGID = new Label();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
string TC = (MSQLRD["Topic"].ToString());
string CT = (MSQLRD["Category"].ToString());
string SM = (MSQLRD["Summary"].ToString());
string BID = (MSQLRD["id"].ToString());
BCIT.TopicSaved1 = TC;
BCIT.CategoriesSaved1 = CT;
BCIT.SummarySaved1 = SM;
BLOGID.Text = BID;
BCIT.TotalBodyStackLayout1.Add("Hello");
}
}
BCITLIST.Add(BCIT);
MSQLRD.Close();
string Query1 = "SELECT * FROM test.blogbodytable where `BlogID` = '" + BLOGID.Text + "' ";
MySqlCommand cmd1 = new MySqlCommand(Query1, conn);
MySqlDataReader MSQLRD1 = cmd1.ExecuteReader();
if (MSQLRD1.HasRows)
{
while (MSQLRD1.Read())
{
string BLOGBODY ;
BLOGBODY = (MSQLRD1["BlogBody"].ToString());
BCIT.TotalBodyStackLayout1.Add(BLOGBODY);
}
}
BCITLIST.Add(BCIT);
conn.Close();
return BCITLIST;
}
from my code the line BCIT.TotalBodyStackLayout1.Add("Hello"); in the first reader does add "hello" to the BCIT.TotalBodyStacklayout1, but the line BCIT.TotalBodyStackLayout1.Add( BLOGBODY); does not work, what am i doing wrong?
Can you be more specific what you mean by 'BCIT.TotalBodyStackLayout1.Add(BLOGBODY);' does not work. Are you getting any exception? or if BLOGBODY coming empty? There are few primitive troubleshooting steps you can perform to nail-down the issue
confirm what BLOGID.Text you are getting from your previous query and corresponding data is available in test.blogbodytable for that id.
if (MSQLRD1.HasRows) is resolving to true
Were you able to get inside while (MSQLRD1.Read())

Error when trying to update a field in datagridview which is outer join

I have two tables called appointment and patient which have relationship with each other. I use outer join on appointment form to display the pFirstName field of patient table instead of the patientID. Now I want to try updating the pFirstName at appointment form, etc changing adam name to something else and clicking update button, but it gives me Invalid column name 'pFirstName'. Only this field cannot work since it is outer join. the other fields like aStatus, aDate works fine. Previously I was using commandbuilder to generate the update so cannot work for outer join for update, so I have to switch to this method which is manually typing the update query. Any help???
APPOINTMENT FORM
APPOINTMENT AND PATIENT TABLE
Column 'patientid' does not belong to table following #Ralf advice
private void LoadAppointmentRecords()
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, pat.pFirstName, cen.mcCentre, nur.nFirstName FROM APPOINTMENT AS app";
strCommandText += " LEFT OUTER JOIN PATIENT as pat on app.patientid = pat.patientid";
strCommandText += " LEFT OUTER JOIN MEDICALCENTRE as cen on app.mcid = cen.mcid";
strCommandText += " LEFT OUTER JOIN NURSE as nur on app.nurseid = nur.nurseid";
/*
string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT";
strCommandText += " AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID";
strCommandText += " Left outer join Patient as p on a.patientid = p.patientId";
strCommandText += " left outer join medicalcentre as m on a.mcID = m.mcid";
*/
AppointmentAdapter = new SqlDataAdapter(strCommandText, myConnect);
//command builder generates Select, update, delete and insert SQL
// statements for MedicalCentreAdapter
// Empty Employee Table first
Appointment.Clear();
// Fill Employee Table with data retrieved by data adapter
// using SELECT statement
AppointmentAdapter.Fill(Appointment);
// if there are records, bind to Grid view & display
if (Appointment.Rows.Count > 0)
grdApp.DataSource = Appointment;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
string strQuery = string.Empty;
string strQuery2 = string.Empty;
DataTable dtChanges;
//
// Get the Updated DataTable back from the DataGridView
DataTable dtAppointment = (DataTable)grdApp.DataSource;
//
// Get the Connection string from App.config.
string strConn = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand();
//
// Get the Modified Rows by filtering on their RowState
dtChanges = dtAppointment.GetChanges(DataRowState.Modified);
if (dtChanges != null)
{
//
// Form the UPDATE Query to Update the Rows.
objConn.Open();
objCmd.Connection = objConn;
for (int i = 0; i < dtChanges.Rows.Count; i++)
{
strQuery = "UPDATE APPOINTMENT SET ";
strQuery += "aDate = '" + dtChanges.Rows[i]["aDate"].ToString() + "',";
strQuery += "pFirstName = '" + dtChanges.Rows[i]["pFirstName"].ToString() + "',";
strQuery += "aStatus = '" + dtChanges.Rows[i]["aStatus"].ToString() + "'";
strQuery += "WHERE appointmentID = '" + dtChanges.Rows[i]["appointmentID"].ToString() + "'";
//strQuery2 = "UPDATE APPOINTMENT SET ";
//strQuery2 += "pFirstName = '" + dtChanges.Rows[i]["pFirstName"].ToString() + "'";
//strQuery2 += "WHERE appointmentID = '" + dtChanges.Rows[i]["appointmentID"].ToString() + "'";
//
// Execute the Update Query.
objCmd.CommandText = strQuery;
objCmd.ExecuteNonQuery();
}
objConn.Close();
dtChanges = null;
MessageBox.Show("Record Updated");
}
else
{
MessageBox.Show("No update to change");
}
}
Trying to follow #Ralf advice I remove the var in each line of using (var objCmd = objConn.CreateCommand()) since it gives me A local variable named 'objCmd' cannot be declared in this scope because it would give a different meaning to 'objCmd', which is already used in a 'parent or current' scope to denote something else. But now i have this error, Column 'patientid' does not belong to table, whatever i try to update.
private void btnUpdate_Click(object sender, EventArgs e)
{
string strQuery = string.Empty;
string strQuery2 = string.Empty;
DataTable dtChanges;
//
// Get the Updated DataTable back from the DataGridView
DataTable dtAppointment = (DataTable)grdApp.DataSource;
//
// Get the Connection string from App.config.
string strConn = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand();
//
// Get the Modified Rows by filtering on their RowState
dtChanges = dtAppointment.GetChanges(DataRowState.Modified);
if (dtChanges != null)
{
using (objConn = new SqlConnection(strConn))
{
objConn.Open();
for (int i = 0; i < dtChanges.Rows.Count; i++)
{
long? patientid = (long?)dtChanges.Rows[i]["patientid"]; // you must return the id in your sql to distinguish a needed INSERT from an UPDATE
if (!patientid.HasValue)
{
using (objCmd = objConn.CreateCommand())
{
objCmd.CommandText = "INSERT INTO Patient(pFirstName) VALUES(#pFirstName); SELECT SCOPE_IDENTITY();";
objCmd.Parameters.AddWithValue("#pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
patientid = (long)objCmd.ExecuteScalar();
}
}
else
{
using (objCmd = objConn.CreateCommand())
{
objCmd.CommandText = "UPDATE Patient SET pFirstName = #pFirstName WHERE patientid = #patientid";
objCmd.Parameters.AddWithValue("#pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
objCmd.Parameters.AddWithValue("#patientid", patientid);
objCmd.ExecuteNonQuery();
}
}
using (objCmd = objConn.CreateCommand())
{
objCmd.CommandText = "UPDATE APPOINTMENT SET aDate = #date, aStatus = #status, patientid = #patientid WHERE appointmentID = #appointmentID";
objCmd.Parameters.AddWithValue("#date", (DateTime)dtChanges.Rows[i]["aDate"]);
objCmd.Parameters.AddWithValue("#status", (string)dtChanges.Rows[i]["aStatus"]);
objCmd.Parameters.AddWithValue("#patientid", patientid);
objCmd.Parameters.AddWithValue("#appointmentID", (long)dtChanges.Rows[i]["appointmentID"]);
objCmd.ExecuteNonQuery();
}
}
objConn.Close();
dtChanges = null;
MessageBox.Show("Record Updated");
}
}
else
{
MessageBox.Show("No update to change");
}
}
I guessed the datatypes in your DataTable and cleaned up the code (especially using Usings and Parameteres). You will need to return the patientid in you select Statement also to get it working this way.
if (dtChanges != null)
{
using(var objConn = new SqlConnection(strConn))
{
objConn.Open();
for (int i = 0; i < dtChanges.Rows.Count; i++)
{
long? patientid = (long?)dtChanges.Rows[i]["patientid"]; // you must return the id in your sql to distinguish a needed INSERT from an UPDATE
if (!patientid.HasValue)
{
using (var objCmd = objConn.CreateCommand())
{
objCmd.CommandText = "INSERT INTO Patient(pFirstName) VALUES(#pFirstName); SELECT SCOPE_IDENTITY();";
objCmd.Parameters.AddWithValue("#pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
patientid = (long)objCmd.ExecuteScalar();
}
}
else
{
using (var objCmd = objConn.CreateCommand())
{
objCmd.CommandText = "UPDATE Patient SET pFirstName = #pFirstName WHERE patientid = #patientid";
objCmd.Parameters.AddWithValue("#pFirstName", (string)dtChanges.Rows[i]["pFirstName"]);
objCmd.Parameters.AddWithValue("#patientid", patientid);
objCmd.ExecuteNonQuery();
}
}
using (var objCmd = objConn.CreateCommand())
{
objCmd.CommandText = "UPDATE APPOINTMENT SET aDate = #date, aStatus = #status, patientid = #patientid WHERE appointmentID = #appointmentID";
objCmd.Parameters.AddWithValue("#date", (DateTime)dtChanges.Rows[i]["aDate"]);
objCmd.Parameters.AddWithValue("#status", (string)dtChanges.Rows[i]["aStatus"]);
objCmd.Parameters.AddWithValue("#patientid", patientid);
objCmd.Parameters.AddWithValue("#appointmentID", (long)dtChanges.Rows[i]["appointmentID"]);
objCmd.ExecuteNonQuery();
}
}
}
}

Check SQL Server table and rows in table, if null create

I need a way to check if a table exist in my database from my C# class, and if that table got the rows needed.
If it doesn't exist or some of the rows are missing, I need to add those.
I've used this method but don't know how to get the missing functions in there.
( Check if a SQL table exists )
I'm working with SQL Server and C#
I'm going to attach a script here that will dump all the objects and columns for the objects in a TempTable. I run the same script on the DB that I'm comparing with, and check which objects doesn't exists, and which columns in which tables does not exist, and which columns have changed. I've used a Delphi app very long ago then to "upgrade" my DB's
I run this code on the MASTER database.
If Exists(Select 1 from sysobjects where name = 'CheckTables')
Drop Table CheckTables
GO
Select o.id oid, o.name oname, c.colid cid, c.name cname, t.name ctype, c.xusertype, c.[length] tlength, c.prec cprec, c.scale cscale, isnullable
into CheckTables
from sysobjects o
inner join syscolumns c on c.id = o.id
inner join systypes t on t.xusertype = c.xusertype
where o.name not like '%dt_%' and o.category <> 2 and o.type = 'U'
order by o.id, c.colid
Delete CheckTables where oname = 'CheckTables'
Then I bcp the data into a flat file
When I ran my upgrade, I create a table on the Upgrade DB with the same structure, and bcp the data of the Master DB in there.
Then I used this script then in my Delphi App to check what changed.
Select oname, cname, ctype, IsNull(tlength, 0), IsNull(cprec, 0), IsNull(cscale, 0), ctype, isnullable from CheckTables hr
where cname not in (Select name from syscolumns where id = object_id(oname)
and length = hr.tlength
and xusertype = hr.xusertype
and isnullable = hr.isnullable)
order by oname
This should get you going.
If you need more information on the C# part of it, I can give you some code.
Here is C# code to get you going. There is some stuff that you will have to add yourself, but if you strugle, let me know.
private void UpgradeDB()
{
SqlConnection conn = new SqlConnection("Some Connection String");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "If 1 = (Select 1 from sysobjects where id = object_id('CheckTables'))\r\n" +
" Drop Table CheckTables\r\n" +
"Create Table CheckTables\r\n" +
"(oid int,\r\n" +
"oname varchar(50),\r\n" +
"colid int,\r\n" +
"cname varchar(50),\r\n" +
"ctype varchar(50),\r\n" +
"cxtype int,\r\n" +
"tlength int,\r\n" +
"cPrec int,\r\n" +
"cScale int,\r\n" +
"isnullable int";
cmd.ExecuteNonQuery();
//BCP your data from MASTER TABLE into the CheckTables of the UpgradeDB
cmd.CommandText = "Select oname, cname, ctype, IsNull(tlength, 0), IsNull(cprec, 0), IsNull(cscale, 0), isnullable from CheckTables hr\r\n" +
"where cname not in (Select name from syscolumns where id = object_id(oname)\r\n" +
"and length = hr.tlength\r\n" +
"and xusertype = hr.xusertype\r\n" +
"and isnullable = hr.isnullable)\r\n" +
"order by oname";
SqlDataReader read = cmd.ExecuteReader();
string LastTable = "";
bool TableExists = false;
bool ColumnExists = false;
while(read.Read())
{
if(LastTable != read[0].ToString())
{
LastTable = read[0].ToString();
TableExists = false;
if (!CheckIfTableExist(LastTable))
TableExists = CreateTable(LastTable);
else
TableExists = true;
}
if (TableExists)
{
if (!CheckIfColumnExists(read[0].ToString(), read[1].ToString()))
{
CreateColumn(read[0].ToString(), read[1].ToString(), read[2].ToString(),
Convert.ToInt32(read[3].ToString()), Convert.ToInt32(read[4].ToString()),
Convert.ToInt32(read[5].ToString()), Convert.ToBoolean(read[6].ToString()));
ColumnExists = false; //You don't want to alter the column if you just created it
}
else
ColumnExists = true;
if(ColumnExists)
{
AlterColumn(read[0].ToString(), read[1].ToString(), read[2].ToString(),
Convert.ToInt32(read[3].ToString()), Convert.ToInt32(read[4].ToString()),
Convert.ToInt32(read[5].ToString()), Convert.ToBoolean(read[6].ToString()));
}
}
}
read.Close();
read.Dispose();
conn.Close();
cmd.Dispose();
conn.Dispose();
}
private bool CheckIfTableExist(string TableName)
{
SqlConnection conn = new SqlConnection("Connection String");
SqlCommand cmd = new SqlCommand();
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Select IsNull(object_id('" + TableName + "'), 0)";
Int64 check = Convert.ToInt64(cmd.ExecuteScalar());
conn.Close();
cmd.Dispose();
conn.Dispose();
return check != 0;
}
private bool CreateTable(string TableName)
{
try
{
//Write your code here to create your table
return true;
}
catch
{
return false;
}
}
private bool CheckIfColumnExists(string TableName, string ColName)
{
SqlConnection conn = new SqlConnection("Connection String");
SqlCommand cmd = new SqlCommand();
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Select IsNull(id, 0) from syscolumns where id = object_id('" + TableName + "') and name = '" + ColName + "'";
Int64 check = Convert.ToInt64(cmd.ExecuteScalar());
conn.Close();
cmd.Dispose();
conn.Dispose();
return check != 0;
}
private void CreateColumn(string TableName, string ColName, string ColType, int Length, int Precision, int Scale, bool Nullable)
{
//Write your code here to create your column
}
private void AlterColumn(string TableName, string ColName, string ColType, int Length, int Precision, int Scale, bool Nullable)
{
//Write your code here to alter your column
}

error: sql command not properly ended

I have to search the employee details, which is contained within 3 tables. I have used joins in the query query, but it shows error when I press the search button:
sql command not properly ended
c# coding:
try {
//Search Employee Details
Oracle.DataAccess.Client.OracleConnection cn = new Oracle.DataAccess.Client.OracleConnection();
cn.ConnectionString = "user id=system; password=system;";
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.Connection = cn;
//cn = new Oracle.DataAccess.Client.OracleConnection();
cmd.CommandText = " select deposit.loanid,
form1.empedoj,
form1.empshare,
sharecapital.shareint,
sharecapital.loandt,
sharecapital.loandeduc,
sharecapital.dividend,
sharecapital.sharetot
from form1,
deposit,
sharecapital
where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "'"; // shows sql command not properly ended
Oracle.DataAccess.Client.OracleDataAdapter ada = new Oracle.DataAccess.Client.OracleDataAdapter(cmd);
System.Data.DataTable dt = new DataTable();
dt.Clear();
ada.Fill(dt);
//Display in Textbox
if (dt.Rows.Count > 0) {
txtlnid.Text = dt.Rows[0].ItemArray[0].ToString();
admdate.Text = dt.Rows[0].ItemArray[1].ToString();
txtadmamt.Text = dt.Rows[0].ItemArray[2].ToString();
txtadmint.Text = dt.Rows[0].ItemArray[3].ToString();
loandt.Text = dt.Rows[0].ItemArray[4].ToString();
txtlnamt.Text = dt.Rows[0].ItemArray[5].ToString();
txtlnint.Text = dt.Rows[0].ItemArray[6].ToString();
txtsctot.Text = dt.Rows[0].ItemArray[7].ToString();
}
if (cn.State == ConnectionState.Closed) {
cn.Open();
}
string str;
str = cmd.ExecuteScalar().ToString();
if (str != null) {
MessageBox.Show("Record Found");
} else {
MessageBox.Show("ID not Match");
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Your SQL statement becomes
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
I suspect it should be:
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID
AND SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
Also, you have a 3-table join without the correct join conditions, the query is highly likely to return a Cartesian product.
Have you tried putting a semicolon at the end of your query string?
cmd.CommandText = " select deposit.loanid, form1.empedoj, form1.empshare,
sharecapital.shareint, sharecapital.loandt, sharecapital.loandeduc,
sharecapital.dividend, sharecapital.sharetot from form1, deposit ,
sharecapital where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "';";

Categories

Resources