Trying to compare a value I get from an input field to a value in a database using mysql, and I get the error :Oracle.DataAccess.Client.OracleException: 'ORA-00911: invalid character'
OracleCommand cmd2 = new OracleCommand();
cmd2.Connection = conn;
cmd2.CommandText = "SELECT Name FROM Actors WHERE EXISTS (SELECT * FROM Actors WHERE Name = Omar ); ";
cmd2.Parameters.Add("name", textBox7.Text);
cmd2.CommandType = CommandType.Text;
reader = cmd2.ExecuteReader();
while (reader.Read())
{
if(reader[0].Equals(1))
{
while (reader.Read())
{
{
ID_VALUE = Convert.ToInt32(reader["ID"]);
}
}
cmd2.CommandText = $"insert into Movies_Actors values(:ID,{ID_VALUE})";
cmd2.Parameters.Add("ID", textBox1.Text);
cmd2.ExecuteNonQuery();
}
else
{
doesnotExist = true;
}
}
Related
I'm using C# console app to update a table with a lot of rows based on the value of two column inside MySQL.
Below is the code that I've tried to update the table.
Is it possible to execute update during dataread while loop or do I need to use other way to accomplish this?
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
Right now if I execute the programs, the data will not be updated and will show error
'There is already an open DataReader associated with this Connection which must be closed first.'
However if I close the connection, it will only execute and update the very first row which satisfy the if-else rule.
I think there must be a way for this to run in a loop without having me to run the program repeating times.
Can anyone suggest how should I fix the code for that?
U can define new connection object for that
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
MySqlConnection con1 = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con1);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
//I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
if(!rdr.read())
{
Console.WriteLine("Update query not working!!!");
}
else
{
//user_email
string usermail = Convert.ToString(user_email);
usermail = rdr[0].ToString();
Console.WriteLine("Username: {0}", usermail.ToString());
//meta_value AS 'Current Points'
string metavalue = Convert.ToString(meta_value);
metavalue = rdr[1].ToString();
Console.WriteLine("metavalue: {0}", metavalue.ToString());
//meta_value AS 'point'
string points = Convert.ToString(point);
points = rdr[2].ToString();
Console.WriteLine("point: {0}", points.ToString());
Console.ReadLine();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
I'm trying to make a private message system.
What I have so far.
- checking if player exists with the name from textbox, if not, error shows up.
Now, I'm trying to insert it to the table. The problem is that the table have 2 colums
to_user_id
from_user_id
And becasuse I'm using a textbox to enter the name of the user, I dont how to retrieve to_user_id from users table while having only name.
this is my code
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
conn.Open();
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
if (flag == true)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
}
else if(flag == false)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #to, #from, #date)";
cmd.Parameters.AddWithValue("#title", TextBox_Title.Text);
cmd.Parameters.AddWithValue("#content", TextBox_Msg.Text.Replace("\n", "<br/>"));
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#from", Session["id"].ToString());
con.Open();
cmd.ExecuteNonQuery();
}
}
Of course I got an error
Conversion failed when converting the nvarchar value 'username' to data type int.
#edit,
#cordan I tried this
DECLARE #user_id = (SELECT id FROM users WHERE user_login=#to );
INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #user_id, #from, #date);
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
got this error
Incorrect syntax near '='.
Must declare the scalar variable "#user_id".
This bit here is a huge NO!!
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
You are selecting every single user from the users table, just to determine if the one you're trying to find exists.
Aside from the fact that you could almost certainly just add:
if (rd[1].ToString() == TextBox_To.Text)
{
foundUserId = (int)rd[0]; // I'm assuming the first column in users is the Id - it probably is
flag = false;
break;
}
DONT DO THAT!!
Instead, you should just be looking for the one username you're interested in
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select top 1 Id from [users] where username=#username";
cmdd.Parameters.AddWithValue("#username",username);
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
var userId = 0;
if(rd.Read())
{
userId = (int)rd[0];
}
conn.Close();
if (userId == 0)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
return;
}
else
.... // userId holds the users Id
...
cmd.Parameters.AddWithValue("#to", userId);
I want to check if the the productID exist in the database and don't allow to update if the the productID does not exist
This is the code I used for checking
bool HasInventory()
{
foreach (ListViewItem item in lvMaterialsList.Items)
{
Label ltr = (Label)item.FindControl("Label1");
string name = ltr.Text;
bool existing = true;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProductID FROM Inventory WHERE ProductID=" + name;
cmd.Parameters.AddWithValue("#ProductID", name);
SqlDataReader data = cmd.ExecuteReader();
if (data.HasRows)
existing = true;
else
existing = false;
con.Close();
return existing;
}
return false;
}
This is the code for the button used to update the database
protected void lvMaterialsList_ItemCommand(object sender, ListViewCommandEventArgs e)
{
bool existingSupply = IsExisting();
bool hasquantity = HasInventory();
Label ltRefNo = (Label)e.Item.FindControl("ltRefNo");
Label Label1 = (Label)e.Item.FindControl("Label1");
TextBox txtAlloted = (TextBox)e.Item.FindControl("txtAlloted");
Literal ltUsed = (Literal)e.Item.FindControl("ltUsed");
int alloted = Convert.ToInt32(txtAlloted.Text);
int productid = Convert.ToInt32(Label1.Text);
if (e.CommandName == "updateused")
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (existingSupply && hasquantity)
{
cmd.CommandText = "UPDATE RequiredMaterials SET Used=Used + #Used WHERE ReqMatID=#ReqMatID";
}
else
{
cmd.CommandText = "UPDATE RequiredMaterials SET Used=#Used WHERE ReqMatID=#ReqMatID";
}
cmd.Parameters.AddWithValue("#Used", alloted);
cmd.Parameters.AddWithValue("#ReqMatID", ltRefNo.Text);
cmd.ExecuteNonQuery();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Inventory SET Quantity = Quantity - #Quantity " +
"WHERE ProductID=#ProductID";
cmd.Parameters.AddWithValue("#Quantity", alloted);
cmd.Parameters.AddWithValue("#ProductID", productid);
cmd.ExecuteNonQuery();
con.Close();
}
GetMaterialsList();
}
I don't know why it keeps on updating..
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
{
.........
}
I'm getting this error
This method or property cannot be called on Null values
on this line id = rd.GetString(0);. How to solve it?
public string MaxId()
{
string id = "";
con.Open();
string sql = "SELECT MAX(id) FROM Customer";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read()){
id = rd.GetString(0);
}
con.Close();
return id;
}
add this
!rd.IsDBNull(0)
before
id = rd.GetString(0);
So, your code would look like
public string MaxId()
{
string id = "";
con.Open();
string sql = "SELECT MAX(id) FROM Customer";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
if(!rd.IsDBNull(0))
id = rd.GetString(0);
}
con.Close();
return id;