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() + "';";
Related
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
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())
I try to updata a single row, chosen by it ID. But what I got at best is an additional row instead of an updated one.
I made several attempts. Now I got a System.InvalidOperationException claiming that a valid InsertCommand is necessary for an update, if a DataRow listing will get a new row.
To me it is the same again: Why insert? I want to update.
Can anybody give me a hint?
This is my related code:
string selectQuery = $"SELECT * FROM Records";
string updateQuery = $"UPDATE Records SET AnyContent = #AnyContent WHERE [ID] = #ID";
OleDbDataAdapter adapter = null;
OleDbCommand cmd = null;
try
{
adapter = new OleDbDataAdapter(selectQuery, ConnectionString);
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = updateQuery;
cmd.Parameters.AddWithValue ("#AnyContent", "066066");
cmd.Parameters.AddWithValue("#ID", 2);
try
{
adapter.UpdateCommand = cmd;
nbRowsChanged = adapter.Update(content);
}
finally
{
adapter?.Close();
cmd?.Close();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
<<< Update >>>
Originally I tried it with an OleDbCommandBuilder before. But CommandBuilder created an update command, which seems to me like an insert command. This is why I tried it without CommandBuilder above. But inserting seems to follow me.
This is my old code, which is closer to where I want to get as it uses a DataTable instead of parameters:
string selectQuery = $"SELECT * FROM Records WHERE [ID] = ?";
OleDbConnection con = null;
OleDbDataAdapter adapter = null;
OleDbCommandBuilder builder = null;
try
{
adapter = new OleDbDataAdapter();
con = new OleDbConnection(ConnectionString);
adapter.SelectCommand = new OleDbCommand(selectQuery, con);
builder = new OleDbCommandBuilder(adapter);
try
{
con.Open();
nbRowsChanged = adapter.Update(content);
logText += "....InsertCommand: " + builder.GetInsertCommand().CommandText + "\n"; // Just to debug
logText += "....UpdateCommand: " + builder.GetUpdateCommand().CommandText + "\n"; // Just to debug
}
finally
{
con?.Close();
adapter?.Dispose();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
logText += tmpText ;
logText += "...Database: Access disposed.\n";
return isSuccess;
And this is the related trace:
LogText:
...Database: Trying to update <1> number of rows in table <Records>
....InsertCommand: INSERT INTO Records (AnyContent) VALUES (?)
....UpdateCommand: UPDATE Records SET AnyContent = ? WHERE ((ID = ?) AND ((? = 1 AND AnyContent IS NULL) OR (AnyContent = ?)))
.... Success: Updated <1> rows.
...Database: Access disposed.
NbRows Before: 5
NbRows After: 6
I am using the same button "Save" to update a table called AnalysisExperiments and also to insert data into a table called "Analysis". however the update is not working. Here is the code:
#region Insert Data into Analysis Table
if (checkIfRepeatedJobNumber(tbJobNumber.Text.Trim()))
{
MessageBox.Show("Job Number is already exist.", "Repeated Data");
return;
}
string query = "insert into Analysis (ID, WellName, EstimatedStartDate, SOWComments, ProgressComments, Field, FocalPoint, StudyCompleted, Company, ReservoirPressure, ReservoirTemp, SelectedSamples) " +
"values (#ID, #WellName, #SamplingDate, #SOWComments, #ProgressComments, #Field, #FocalPoint, #StudyCompleted, #Company, #ReservoirPressure, #ReservoirTemp, #SelectedSamples)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("#ID", tbJobNumber.Text);
cmd.Parameters.AddWithValue("#WellName", tbWellName.Text);
cmd.Parameters.AddWithValue("#SamplingDate", dtpSamplingDate.Text);
cmd.Parameters.AddWithValue("#SOWComments", tbSOW_Comments.Text);
cmd.Parameters.AddWithValue("#ProgressComments", tbProgressComments.Text);
cmd.Parameters.AddWithValue("#Field", tbFieldName.Text);
cmd.Parameters.AddWithValue("#FocalPoint", tbFocalName.Text);
if (radYes.Checked)
cmd.Parameters.AddWithValue("#StudyCompleted", "Yes");
else
cmd.Parameters.AddWithValue("#StudyCompleted", "No");
cmd.Parameters.AddWithValue("#Company", tbCompany.Text);
cmd.Parameters.AddWithValue("#ReservoirPressure", tbReservoirPressure.Text);
cmd.Parameters.AddWithValue("#ReservoirTemp", tbReservoirTemp.Text);
cmd.Parameters.AddWithValue("##SelectedSamples", tbSelectedSamples.Text);
try
{
conn.Open();
int j = cmd.ExecuteNonQuery();
if (j == 1)
{
MessageBox.Show("Done");
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
#endregion
#region update analysis Exp but still no working
#region Update database
try
{ int k = 0;
OleDbDataAdapter da;
da = new OleDbDataAdapter("select* from [AnalysisExperiments]", conn);
string ExpQuery = "update AnalysisExperiments set SampleNumber = #SampleNumber, Status = #Status where ID = '" + tbJobNumber.Text + "' and Experiment = '";
foreach (DataGridViewRow row in dgvExperiments.Rows)
{
ExpQuery += row.Cells["Experiment"].Value.ToString() + "'";
OleDbCommand updateCommand = new OleDbCommand(ExpQuery, conn);
updateCommand.Parameters.Add("#SampleNumber", OleDbType.VarWChar);
MessageBox.Show(row.Cells["SampleNumber"].Value.ToString() + " | " + row.Cells["Status"].Value.ToString() + " | " + row.Cells["Experiment"].Value.ToString());
updateCommand.Parameters["#SampleNumber"].Value = row.Cells["SampleNumber"].Value.ToString();
updateCommand.Parameters.Add("#Status", OleDbType.Boolean);
updateCommand.Parameters["#Status"].Value = row.Cells["Status"].Value;
da.UpdateCommand = updateCommand;
conn.Open();
k = da.UpdateCommand.ExecuteNonQuery();
conn.Close();
}
if (k == 1)
MessageBox.Show("Done");
else
{
MessageBox.Show("Nothing Updated!");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
#endregion
knowing that the compiler skips the loop in the update region.
At the second loop the query syntax becomes invalid cause the += that concatenates the previous text with the new one
Dim newQuery = ExQuery + row.Cells["Experiment"].Value.ToString() + "'";
And then use the new string for the ExecuteNonQuery.
Still this approach has many problems. You should separate this code in different methods and use parameters also for the last value
Have you tried to debug the foreach line to see if there are any rows in your dgvExperiments and if they are of type (or subtype of) DataGridViewRow ?
I am using the below code to grab the page tiles, meta description from database created in SQL Server 2005. My site is built with ASP.NET 2.0 and C#.
On page_load I am executing this code:
string query = "select MetaDescription, MetaKeywords, H1Text, Ptitle, H2Text FROM SeoText Where CatalogItemId ='" + this.CurrentEnsemble.ItemId + "'";
SqlConnection myconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBconnection"].ConnectionString);
SqlCommand SqlCmd = null;
SqlCmd = new SqlCommand(query, myconnection);
SqlDataAdapter ad = new SqlDataAdapter(SqlCmd);
DataTable dt = new DataTable();
ad.Fill(dt);
if (dt.Rows[0]["Ptitle"].ToString() == "")
{
this.Page.Title = this.CurrentEnsemble.Title;
}
else
{
this.Page.Title = this.CurrentEnsemble.Title + " " + dt.Rows[0]["Ptitle"].ToString();
}
HtmlMeta metaDesc = (HtmlMeta)Page.Header.FindControl("metaDesc");
if (dt.Rows[0]["MetaDescription"].ToString() == "")
{
metaDesc.Attributes.Add("Content", this.CurrentEnsemble.Title );
}
else
{
metaDesc.Attributes.Add("Content", dt.Rows[0]["MetaDescription"].ToString());
}
HtmlMeta metaKey = (HtmlMeta)Page.Header.FindControl("metaKey");
if (dt.Rows[0]["MetaKeywords"].ToString() == "")
{
metaKey.Attributes.Add("Content", "site general text");
}
else
{
metaKey.Attributes.Add("Content", dt.Rows[0]["MetaKeywords"].ToString());
}
HtmlGenericControl h1 = (HtmlGenericControl)Master.Master.Master.FindControl("h1top");
if (dt.Rows[0]["H1Text"].ToString() == "")
{
h1.InnerText = "site general text";
}
else
{
h1.InnerText = this.CurrentEnsemble.Title + " " + dt.Rows[0]["H1Text"].ToString();
}
HtmlGenericControl h2 = (HtmlGenericControl)Master.Master.Master.FindControl("h2bottom");
if (dt.Rows[0]["H2Text"].ToString() == "")
{
h2.InnerText = "site general text";
}
else
{
h2.InnerText = this.CurrentEnsemble.Title + " " + dt.Rows[0]["H2Text"].ToString();
}
The error is thrown at
ad.Fill(dt)
I am not sure where I am making the mistake.
Thanks and appreciate it
Try adding with (nolock) statements to your statment. Similar problem here: SqlDataAdapter.Fill() Timeout - Underlying Sproc Returns Quickly