Why is this insert not working?` - c#

Actually my code was suppose to check that is there any value in the course_choice_teacher table. If there is not, then it will insert some values into the table. Now this time there is no value in the table. So dr2.Read() should return false and do the else portion. But it is doing the reverse thing. I'll be very happy if you help me in this purpose.
string oradb = "Data Source=localhost;User Id=system;Password=cse;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd2 = new OracleCommand();
cmd2.Connection = conn;
cmd2.CommandText = "select * from course_choice_teacher where teacher_id='"+teacher_home.st+"' and choice_no=1";
cmd2.CommandType = CommandType.Text;
OracleDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
MessageBox.Show("Already Given");
}
else
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into course_choice_teacher values('" + teacher_home.st + "','" + dataGridView1.CurrentRow.Cells["course_id"].Value.ToString() + "',1)";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
}
conn.Dispose();

The datareader has property .HasRows to check if the result has some rows. This would be a proper way to check what you intend to do.
if (dr2.HasRows)
{
MessageBox.Show("Already Given");
}
else
{
.........
}

Related

INSERT INTO Syntax error C# access database

When executing this query with parameters added as values, i get an error saying my syntax is wrong. I tried following multiple tutorials, looking up questions here is stack overflow, and when comparing, they seem the same, but mine does not seem to work.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\\Users\\fidyc\\OneDrive\\Desktop\\ProgrII.accdb";
OleDbCommand cmd = new OleDbCommand("INSERT Product_Orders(order_ID,plankCount,thickness,width,height)VALUES(#order_ID, #plankCount, #thickness, #width, #height)");
cmd.Parameters.Add("#order_ID", OleDbType.Integer).Value = orderID;
cmd.Parameters.Add("#plankCount", OleDbType.Decimal).Value = plankCount;
cmd.Parameters.Add("#thickness", OleDbType.Decimal).Value = thickness;
cmd.Parameters.Add("#width", OleDbType.Decimal).Value = width;
cmd.Parameters.Add("#height", OleDbType.Decimal).Value = height;
cmd.Connection = con;
con.Open();
if (con.State == ConnectionState.Open)
{
/*try
{*/
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
/*}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
con.Close();
}*/
}
Edit: values are passed to the function
public static void Push(int orderID, decimal plankCount, decimal thickness, decimal width, decimal height)
{
The problem turned out to be the count column name, as sql has a count command, it needs to be
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,[count],thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
instead of
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,count,thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"INSERT INTO bookRated "+
"([firstName], [lastName]) "+
"VALUES(#firstName, #lastName)";
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#firstName", firstName),
new OleDbParameter("#lastName", lastName),
});
cmd.ExecuteNonQuery();
}

How do I get last input to column (ID)

I have this code that is suppose to get me the last registered MemberId from column but I cant get it to work, what have I got wrong?
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT top 1 * FROM Medleminfo ORDER BY MemberId desc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
last_id = Convert.ToInt32(dr["MemberId"].ToString());
}
return last_id;
Output last_id is supposed to be used in this method:
public DataTable display_tiger_info(int member_id)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT Medleminfo.MemberId, Medleminfo.Förnamn, Medleminfo.Efternamn,
Medleminfo.Adress, Medleminfo.Telefon, Tigerinfo.Tigernamn,Tigerinfo.Födelsedatum
FROM Medleminfo, Tigerinfo WHERE Medleminfo.MemberId = Tigerinfo.OwnerID ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
Why not just use the 'Max' function? This is assuming that your looking for the largest number in the sequence. The way your question is worded though would suggest that you should have a date column to search by instead. Also if you want just one result then try execute scalar instead of putting it into a data table and going through all that extra work.
int id = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("Select Max(MemberId) from Medleminfo", connection))
{
id = (int)command.ExecuteScalar();
}
}
I think your issues is probably cmd.ExecuteNonQuery() according to the msdn SqlCommand.ExecuteNonQuery Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
You will probably be wanting to use ExecuteReader in something like the following
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//All you want is the member Id why get all the columns
cmd.CommandText = "SELECT top 1 MemberId FROM Medleminfo ORDER BY MemberId desc";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
last_id = Convert.ToInt32( reader[0]));
}
return last_id;
UPDATE: This code might solve your problem but I did not identify the issue correctly cmd.ExecuteNonQuery() should be removed it is not doing anything. adapter.Fill() should be executing the command and I do not know why you are not getting the expected response.

How to pass parameters in a oracle SQL query?

For the past few days I cannot pass any fixed parameters to my SQL query.
I try all possible tutorials to pass the parameter to a query, but nothing works.
However, I have seen by putting fixed parameters directly in the query (method 1) it worked perfectly.
I do not see that in method 2 prevents the functioning of my function.
When I say that it does not work is that in the first method my reader is filled while in the method 2 my reader is empty
method 1 : works (i don't need this kind of function)
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet='demonstration'";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}
method 2 : doesn't works (I need this kind of function)
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet=:test";
cmd.Parameters.Add(new OracleParameter("test", "demonstration"));
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}
String updateCmd;
SqlCommand myCommandUpd;
updateCmd = "UPDATE RHRMVacationRequest SET [EmplId] = #Emplid WHERE RecId = #RecId";
myCommandUpd = new SqlCommand(updateCmd, DataBase.GetConnetionToBase());
myCommandUpd.Parameters.Add(new SqlParameter("#Emplid", SqlDbType.VarChar, 10));
myCommandUpd.Parameters.Add(new SqlParameter("#RecId", SqlDbType.BigInt));
myCommandUpd.Parameters["#Emplid"].Value = emplIdUpd.Text.Trim();
myCommandUpd.Parameters["#RecId"].Value = Convert.ToInt64(RecIdUpd.Value.Trim());
myCommandUpd.Connection.Open();
myCommandUpd.ExecuteNonQuery();
may be i recall the wrong way round - maybe i tried :? and it did not work and used :test - but i think i got you issue, check the code below.
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet=:test";
cmd.Parameters.Add(new OracleParameter(":test", "demonstration"));
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}
After many hours of research, i have I finally found the solution:
public Boolean VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
string str = "demonstration";
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.BindByName = true;
cmd.CommandText = "select * from analyses where nom_projet='"+str+"'";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Console.WriteLine("Data already exist");
return true;
}
Console.WriteLine("Data doesn't already exist");
return true;
}

c# ado.net sqlparameter fails

I am passing sqlparameter in localize language (Persian) from c# but no rows retrieves. Database already collate for persioan_100_ci_ai and tables are collate database_default
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]=#UserName AND [Pwd]=#Password";
cmd.commandtext = qry;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = "ادمین";
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = "ادمین";
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
It works in SSMS
declare #UserName nvarchar(50) = 'ادمين'
declare #Password nvarchar(50)= 'ادمين'
select * from Users where [name]=#UserName and [Pwd] = #Password
It even works when I am embedding variables in query instead of parameter
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
string pLoginName = "ادمین";
string pPassword = "ادمین";
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]='" + pLoginName + "' AND [Pwd]='" + pPassword + "'";
cmd.CommandText = qry;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
Cannot figure out where I am wrong.
Please, if any one can point out.
I don't have any problems, I add both values to my test database. Here is the sample code
// Code in BO logic method
string email = "ادمین";
string password = "ادمین";
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Register WHERE Email=#Email AND Deleted=0 AND Password=#Pass");
cmd.Parameters.AddWithValue(#"Email", email.Trim());
cmd.Parameters.AddWithValue(#"Pass", password.Trim());
DataSet dst = Varmebaronen.AppCode.DA.SqlManager.GetDataSet(cmd);
//DataAccess Methods !
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
DataSet had one record, try to use AddWithValue. If again nothing happen the problem is not in the parameters !
P.S Don't use one static connection, application pool is your friend !
Try seperating out the parameter and value assignment like below:
// Create the parameter objects as specific as possible.
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#Password", System.Data.SqlDbType.NVarChar, 50);
// Add the parameter values. Validation should have already happened.
cmd.Parameters["#UserName"].Value = "ادمین";
cmd.Parameters["#Password"].Value = "ادمین";
Try to use this:
cmd.Parameters.Add(new SqlParameter("#Password", "ادمین"));
EDIT:
Lets try a different way. If you're up for some re-coding. I will post an example from an old college project that works. It's essentially the same concept. May not be the best way but it works...
I used a DataAdapter, a DataSet, and a GridView control on an .aspx page. You tagged ASP.net, but I am not sure what you're trying to use to display the data.
string selectsql2 = "SELECT * FROM [dbo].Event_View WHERE (EventName LIKE '%' + #EventName + '%')";
SqlConnection connect2 = new SqlConnection(connectionstring2);
SqlCommand cmd = new SqlCommand(selectsql2, connect2);
SqlParameter pm = new SqlParameter("#EventName", txtEvents.Text);
cmd.Parameters.Add(pm);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
gvEvents.DataSource = ds2;
gvEvents.DataBind();

MS Access database not updating

Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video

Categories

Resources