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
}
Related
I created a C# application to query and insert a product database. However I am here with a small doubt and if anyone can help me i thank you right away.
The following is:
I have a form to insert data into the database created in MS Access 2007, with the values of reference, sale number, client code, client name, quantity and position number in archive;
Here is my code until the moment:
private void btn_save_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=product.accdb");
OleDbCommand check_sn = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([sn] = #sn)", con);
OleDbCommand check_reference = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([reference] = #ref)", con);
OleDbCommand check_number = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([number] = #num)", con);
con.Open();
check_reference.Parameters.AddWithValue("#ref", textBox_ref.Text);
check_sn.Parameters.AddWithValue("#sn", textBox_sn.Text);
check_number.Parameters.AddWithValue("#num", textBox_num.Text);
int refExist = (int)check_reference.ExecuteScalar();
int SNExist = (int)check_sn.ExecuteScalar();
int numExist = (int)check_number.ExecuteScalar();
if (refExist > 0)
{
MessageBox.Show("A product with this reference already exists....!");
}
else if (SNExist> 0)
{
MessageBox.Show("A product with this sale number already exists....!");
}
else if (numExist > 0)
{
MessageBox.Show("A product with this archive number already exists....!");
}
else
{
try
{
String reference = textBox_ref.Text.ToString();
String sn = textBox_ov.Text.ToString();
String cod_client = textBox_cod.Text.ToString();
String client = textBox_cliente.Text.ToString();
String qtd = textBox_qtd.Text.ToString();
String number = textBox_num.Text.ToString(); //This will be the incremented number
String my_query = "INSERT INTO product(reference,sn,cod_client,client,qtd,number)VALUES('" + reference + "','" + sn + "','" + cod_client + "','" + client + "','" + qtd + "','" + number + "')";
OleDbCommand cmd = new OleDbCommand(my_query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
con.Close();
}
cleanTextBoxes(this.Controls);
}
}
private void search_btn_Click(object sender, EventArgs e)
{
Form search = new Form_search();
search.Show();
this.Hide();
}
}
}
How can i make it so that instead of manually entering the position number in archive in the textbox it can be automatically filled with the new position in archive. For example, my last product inserted has the position 50 in archive, the new one will automatically be number 51 and so on ... and this number should appear automatically in the textbox so that the user knows what is the number of the new registered product.
Thank you,
Ok i have tried this and works but how i do now to increment this value +1?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Aneis_Calibre.accdb");
con.Open();
OleDbDataReader myReader = null;
OleDbCommand number = new OleDbCommand("SELECT TOP 1 [number] FROM product Order by [number] desc", con);
myReader = number.ExecuteReader();
while (myReader.Read())
{
textBox_num.Text = (myReader["number"].ToString());
}
con.Close();
Inside your query, you would want to do something along these lines.
INSERT ...
OUTPUT inserted.identity_column
VALUES (...)
That will return a row with a value for the id. The identity column in SQL will always increment automatically for you. Which would alleviate your approach where you grab the last record and do:
int.TryParse(reader["..."]?.ToString(), out int id);
textbox.Text = id++;
By using the scalar, or reader though I would recommend scalar if you return a single column with a modified SQL query would result in the exact newly inserted id.
I am using C# to create a windows form.
I am trying to set a condition statement for a particular value that is retrieved from my database by the onclick of a button. The datatype of the column is 'integer'.
Below is my code:
string checkquantity = "SELECT `inventory_item`.`Item_Quantity_Available`FROM `inventory_item` , `patient`, `out_treatment`WHERE `inventory_item`.`Item_ID` = `out_treatment`.`Inventory_ID`AND `patient`.`Patient_ID` = `out_treatment`.`Patient_ID`AND `out_treatment`.`Patient_ID`= '" + pid + "' ";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
MySqlDataAdapter selectdata = new MySqlDataAdapter(checkquantity, connect);
DataTable selecttable = new DataTable();
selectdata.Fill(selecttable);
DataSet ds = new DataSet();
selectdata.Fill(selecttable);
selectdata.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if ( i <= 0)
{
MessageBox.Show("Out of Stock");
}
I'm new with c#.
I don't think the int i = ds.Tables[0].Rows.Count; is the right way.
Any help is much appreciated.
First of all, like #Flydog57 said, you should not concatenate your sql query. The best way is to use parameters, for example:
string checkquantity = "SELECT i.Item_Quantity_Available " +
" FROM inventory_item i JOIN out_treatment t ON i.Item_Id = t.Inventory_ID " +
" JOIN patient p ON t.Patient_ID = p.PatiendID " +
" WHERE t.Patient_ID = #Patiend_ID";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
// set the parameter value
selectout.Parameters.AddWithValue("#Patiend_ID", patient_id_value);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
if ((int)rdr["Item_Quantity_Available"] == 0)
MessageBox.Show("Out of Stock");
}
In second place, you could use a MySqlDataReader to verify that Item_Quantity_Available is equal to 0, like in the previous example. Otherwise, If you just wants to verify if there is data, the condition could be something like that:
if (!rdr.Read())
{
MessageBox.Show("Out of Stock");
}
The third improvemente is to join tables with the join clause.
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();
}
}
}
}
My table structure is as follows:
Session
--------------
SessionID (PK)
RoomID
SessionDate
SessionTimeStart
SessionTimeEnd
I have a following query which will always return one row and display in DGV. I use DataAdapter for connection:
DataTable queryResult = new DataTable();
string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
SqlCommand command = new SqlCommand(query, MyConn);
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(queryResult);
I would like to save the query result into multiple strings representing table columns, i.e.
SessionIDstring = query result for SessionID column
RoomIDstring = query result for RoomID column
and so on...
Is it possible to achieve it using one query, or do I have to create 5 queries for each column?
Something similar to this, perhaps, using ADO.NET?
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
using (var connection = new SqlConnection(ConnStr))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
// Note that reader[x] has the equivalent type to the type
// of the returned column, converted using
// http://msdn.microsoft.com/en-us/library/cc716729.aspx
// .ToString() if the item isn't null is always ok
string SessionIDstring = reader[0].ToString(); // it should be an int
// reading it twice is ok
int RoomID = (int)reader[1]; // it should be an int
string RoomIDstring = reader[1].ToString(); // it should be an int
if (reader.Read())
{
throw new Exception("Too many rows");
}
}
else
{
throw new Exception("No rows");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This code was adapted from MSDN ADO.NET Code Examples. I added some usings and made it single row. I don't even want to know why MSDN examples don't go the full length with using.
Note that SqlDataAdapter are built to recover multiple rows/big data and put them in a DataSet. You can use them for single row data, but it's much easier to simply use a SqlDataReader if you only want to fill some variables.
declare #col1 int
declare #col2 varchar(42)
select #col1 = col1
, #col2 = col2
, ....
You could create a class like so...
public class SessionDto
{
public string SessionID {get; set;}
public string RoomID {get; set;}
public string SessionDate {get; set;}
public string SessionTimeStart {get; set;}
public string SessionTimeEnd {get; set;}
}
And then have a method that takes a Room ID and builds your session object
public SessionDto GetSessionData(int roomId)
{
using (var cnn = new SqlConnection(ConnStr))
{
SessionDto sessionDto;
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
cnn.Open();
using (var cmd = new SqlCommand(query,cnn))
{
cmd.Parameters.Add("#RoomID", SqlDbType.Char).Value = roomId;
using (var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
sessionDto = new sessionDto{
SessionID = rdr.GetString(0),
RoomID = rdr.GetString(1),
SessionDate = rdr.GetString(2),
SessionTimeStart = rdr.GetString(3),
SessionTimeEnd = rdr.GetString(4)
};
}
}
}
}
}
return sessionDto;
}
A lot of this is hand typed as I havent got access to VS right now,
but you should get it to work.
Also, I have used rdr.GetString(), there are other methods for GetType().
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() + "';";