Could someone tell me what I'm doing wrong? I've tried to accomplish this in numerous different ways, but have not been able to. Without adding the parameters in, the form runs, but I need the parameters so that I can update records if it so evaluates. I may be off track, so any help is very appreciated.
For example, if a product code is entered and doesn't have a date already, the form should update the date with the current date/time. If the product code does have a date already, it should notify the user that the product has already shipped, else telling the user that the product is not in the database.
It evaluates by querying if there is a product code and if the date is null. If that evaluates to be true, then it should update that product code with a current timestamp in the date column. If that evaluates to be false, it checks to see if the product code exists in the table at all. If it does and the date column is not null, it reports that the product has already shipped, else, it reports that the product doesn't exist in the database.
Without the following parameters, it runs fine, providing the correct responses but, of course, it doesn't ever call to update a record.
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
With these parameters added in, I get an error stating the "The name 'command2' does not exist in the current context. But, I only get this error one. Sorry if my code is way out of line. Thanks in advance for your help!
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
try
{
connection.Open();
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + " and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows)
{
string sql2 = #"UPDATE [products] SET date=#Value2 where PRODUCT_ID=#Value1";
using (SqlCommand command2 = new SqlCommand(sql2, connection))
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
pageBody.Attributes.Add("bgcolor", "#9aff8e");
Label1.Text = "Item " + TextBox1.Text + " Recorded!";
TextBox1.Text = "";
}
else
{
reader.Close();
string sql3 = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + "";
using(SqlCommand command3 = new SqlCommand(sql3, connection))
{
using(SqlDataReader reader2 = command3.ExecuteReader())
{
if (reader2.HasRows)
{
pageBody.Attributes.Add("bgcolor", "#fbff8e");
Label1.Text = "Item " + TextBox1.Text + " Already Shipped!";
TextBox1.Text = "";
}
else
{
pageBody.Attributes.Add("bgcolor", "#ff8e8e");
Label1.Text = "Item " + TextBox1.Text + " Not Found!";
TextBox1.Text = "";
}
}
}
}
}
}
}
finally
{
if(connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
}
Put your parameters assignment inside a bracket and don't forget to call the execute method.
using (var command2 = new SqlCommand(sql2, connection))
{
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
command2.ExecuteNonQuery();
}
using (SqlCommand command2 = new SqlCommand(sql2, connection)) {
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
}
Forgot your brackets.
Related
I am using winform C#,
database name "School"
my "fees" table has 2 columns,
stu_id,fees
The issue I am facing is that it adds multiple (same) entries into the database instead of single.
I have code on other forms but I don't know why is this happening here, any help would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SchoolManagementSystem
{
public partial class Fees : Form
{
public Fees()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
try
{
string str = " INSERT INTO fees VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Your Fees Submitted..");
this.Hide();
Home obj2 = new Home();
obj2.ShowDialog();
}
this.Close();
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
textBox2.Text = "";
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
if (textBox1.Text != "")
{
try
{
string getCust = "select name,standard,medium from student where std_id=" + Convert.ToInt32(textBox1.Text) + " ;"; // saving new custmer info
SqlCommand cmd = new SqlCommand(getCust, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.Read())
{
label9.Text = dr.GetValue(0).ToString();
label6.Text = dr.GetValue(1).ToString();
label7.Text = dr.GetValue(2).ToString();
}
else
{
MessageBox.Show("Sorry '" + textBox1.Text + "' This Registration Id is Invalid, Please Insert Correct Id");
textBox1.Text = "";
textBox2.Text = "";
}
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void Fees_Load(object sender, EventArgs e)
{
}
}
}
when I enter fees from front end, it adds same 2 rows into database instead of 1.
Because you're executing your INSERT statement twice:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why? Why do you even need the SqlDataReader? Just execute the INSERT once:
cmd.ExecuteNonQuery();
MessageBox.Show("Your Fees Submitted..");
If you want to confirm that a row was inserted, ExecuteNonQuery returns the number of rows affected:
var rows = cmd.ExecuteNonQuery();
if (rows != 1)
{
// handle error
}
else
{
MessageBox.Show("Your Fees Submitted..");
}
You are executing the command twice here:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why are you calling ExecuteReader when there's nothing to read? ExecuteReader is for when you execute a SELECT statement with multiple columns and/or multiple rows and you want to read the result set. For an INSERT statement, you only need to call ExecuteNonQuery... because it's not a query.
I read a string using this format with a data reader. How can I read in a date using similar format?
while (MyReader.Read())
{
TextBox1.Text = (string)MyReader["Note"];
}
Try as given below:
while (MyReader.Read())
{
TextBox1.Text = Convert.ToDateTime(MyReader["DateField"]).ToString("dd/MM/yyyy");
}
in ToString() method you can change data format as per your requirement.
If the query's column has an appropriate type then
var dateString = MyReader.GetDateTime(MyReader.GetOrdinal("column")).ToString(myDateFormat)
If the query's column is actually a string then see other answers.
(DateTime)MyReader["ColumnName"];
OR
Convert.ToDateTime(MyReader["ColumnName"]);
This may seem slightly off topic but this was the post I came across when wondering what happens when you read a column as a dateTime in c#. The post reflects the information I would have liked to be able to find about this mechanism. If you worry about utc and timezones then read on
I did a little more research as I'm always very wary of DateTime as a class because of its automatic assumptions about what timezone you are using and because it is way too easy to confuse local times and utc times.
What I'm trying to avoid here is DateTime going 'oh look the computer I'm being run on is in timezone x, therefore this time must also be in timezone x, when I get asked for my values I'll reply as if I'm in that timezone'
I was trying to read a datetime2 column.
The date time you will get back from sql server will end up being of Kind.Unspecified this seems to mean it gets treated like UTC, which is what I wanted.
When reading a date column you also have to read it as a DateTime even though it has no time and is even more prone to screwing up by timezones (as it is on midnight).
I'd certainly consider this to be safer way of reading the DateTime as I suspect it can probably be modified by either settings in sql server or static settings in your c#:
var time = reader.GetDateTime(1);
var utcTime = new DateTime(time.Ticks, DateTimeKind.Utc);
From there you can get the components (Day, Month, Year) etc and format how you like.
If what you have is actually a date + a time then Utc might not be what you want there - since you are mucking around on the client you may need to convert it to a local time first (depending on what the meaning of the time is). However that opens up a whole can of worms.. If you need to do that I'd recommend using a library like noda time. There is TimeZoneInfo in the standard library but after briefly investigating it, it doesn't seem to have a proper set of timezones. You can see the list provided by TimeZoneInfo by using the method TimeZoneInfo.GetSystemTimeZones();
I also discovered sql server management studio doesn't convert times to local time before displaying them. Which is a relief!
I know that this is an old question, but I'm surprised that no answer mentions GetDateTime:
Gets the value of the specified column as a DateTime object.
Which you can use like:
while (MyReader.Read())
{
TextBox1.Text = MyReader.GetDateTime(columnPosition).ToString("dd/MM/yyyy");
}
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
};
}
OR
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = GetValue<int>(reader["conId"]),
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
};
}
// Base methods
protected T GetValue<T>(object obj)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return default(T);
}
protected T GetValue<T>(object obj, object defaultValue)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return (T)defaultValue;
}
In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Library
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
SqlCommand com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Entry Added");
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr, dr1,dr2;
con.Open();
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
dr1 = com1.ExecuteReader();
dr1.Read();
string i = dr1["BookStatus"].ToString();
if (i =="1" )
{
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
dr2 = com2.ExecuteReader();
dr2.Read();
MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );
}
else
{
con.Close();
con.Open();
dr = com.ExecuteReader();
dr.Read();
MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
}
con.Close();
}
else
{
MessageBox.Show("This Book is not available in the library");
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
con.Open();
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
textBox4.Text = dateofissue;
textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
MessageBox.Show("Book Isuued");
}
else
{
MessageBox.Show("Book Not Found");
}
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
con.Open();
SqlCommand com = new SqlCommand(query1, con);
com.ExecuteNonQuery();
string today = DateTime.Today.ToString("dd-MM-yyyy");
DateTime today1 = DateTime.Parse(today);
string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlDataReader dr;
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
dr = cmd.ExecuteReader();
dr.Read();
string DOR = dr["DateOfReturn"].ToString();
DateTime dor = DateTime.Parse(DOR);
TimeSpan ts = today1.Subtract(dor);
string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
int x = int.Parse(ts.Days.ToString());
if (x > 0)
{
int fine = x * 5;
textBox6.Text = fine.ToString();
MessageBox.Show("Book Received\nFine=" + fine);
}
else
{
textBox6.Text = "0";
MessageBox.Show("Book Received\nFine=0");
}
con.Close();
}
}
}
I've had an ASP.NET page that had worked for quite a while, up until recently. The page contains a single text box (TextBox1) and a submit button. When you input (or scan) a number into the field and submit it, if the record exists in the database and hasn't been submitted before, it adds a date/time stamp to another column and gives the user feedback that it's been recorded. If the record exists and already had a date/time stamp, it doesn't change anything but gives the user feedback that the record already has been input or scanned. If the record doesn't exist, it gives the user feedback that there is no such record.
This all worked fine when I was inputting numerical values. Now, the numeric values have changed to alphanumeric and I'm getting and error. Anytime I input a value that is alphanumeric, I get an
Incorrect syntax near 'x'
error that refers to line 35:
using(SqlDataReader reader = command.ExecuteReader())
My entire code from my aspx.cs file is below. Any suggestions are greatly appreciated!
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
try
{
connection.Open();
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + " and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows)
{
string sql2 = #"UPDATE [products] SET date=#Value2 where PRODUCT_ID=#Value1";
using (SqlCommand command2 = new SqlCommand(sql2, connection))
{
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
command2.ExecuteNonQuery();
}
pageBody.Attributes.Add("bgcolor", "#9aff8e");
Label1.Text = "Item " + TextBox1.Text + " Recorded!";
TextBox1.Text = "";
}
else
{
reader.Close();
string sql3 = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + "";
using(SqlCommand command3 = new SqlCommand(sql3, connection))
{
using(SqlDataReader reader2 = command3.ExecuteReader())
{
if (reader2.HasRows)
{
pageBody.Attributes.Add("bgcolor", "#fbff8e");
Label1.Text = "Item " + TextBox1.Text + " Already Shipped!";
TextBox1.Text = "";
}
else
{
pageBody.Attributes.Add("bgcolor", "#ff8e8e");
Label1.Text = "Item " + TextBox1.Text + " Not Found!";
TextBox1.Text = "";
}
}
}
}
}
}
}
finally
{
if(connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
}
First of all: Never do string concatenation for SQL with user input. It opens up risk for Sql Injection which can destroy your database.
The error is due to the change in datatype of PRODUCT_ID from number to string. Add ' to fix the error.
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = '#Value1' and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Value1", TextBox1.Text);
...
}
I hope since you are inputing a alphanumeric field, you have to use. (Note the quotes beside textbox text )
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = '" + TextBox1.Text + "' and DATE is null";
As you are saying its a alphanumeric field, you have to search your product_id by enclosing it as a string.
(Assuming datatype of PRODUCT_ID in your table is varchar. If your datatype is not VARCHAR, you might still see an error )
And yes, As #Faruq mentioned, make sure to update your code to use command parameters to avoid SQL injections.
Change:
PRODUCT_ID = " + TextBox1.Text + "
TO:
PRODUCT_ID = '" + TextBox1.Text + "'
You need to quote the text, so abc should be 'abc' when it gets to the database.
I get this error "ora-00928 missing select keyword" when using a button to submit the query. I have other queries on other buttons and the select statements work but for some reason the insert statement doesnt work.
I've seen other posts on this error but nothing seems to help mine
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Oracle
{
public partial class Register : Form
{
string name;
int pass;
int repass;
string email;
public Register()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=DESKTOP-HQCK6F1:1521/CTECH;Persist Security Info=True;User ID=system;Password=G4ming404;Unicode=True");
OleDbCommand cmd = new OleDbCommand();
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
cmd.Connection = con;
cmd.CommandText = "INSERT INTO SYSTEM.CUSTOMER('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')" + "VALUES('%"+ null + "%','%'" + txtname.Text + "%','%'" + txtemail.Text + "%','%'" + txtpass.Text + "%')";
con.Open();
if (pass == repass)
{
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else {
MessageBox.Show("Success!");
}
MessageBox.Show("User has been created");
this.Close();
Form1 login = new Form1();
login.Show();
}
else {
MessageBox.Show("Password mismatch");
}
con.Dispose();
}
There are some problems in your query.
First you don't need single quotes around the column names, You need double quotes only if any of your columns has the same name as a reserved keyword.
Second problem is the string concatenation of the input boxes text to the query command. This should be avoided at all cost because it is the source of parsing problems and sql injection hacks. Use parameters instead.
Finally your OleDbConnection should be local to your method and inside a using statement to ensure correct disposing of the unmanaged resources also in case of exceptions
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
if (pass != repass)
{
MessageBox.Show("Password mismatch");
return;
}
string cmdText = #"INSERT INTO SYSTEM.CUSTOMER
(CUSTOMER_NAME, CUSTOMER_EMAIL, CUSTOMER_PASSWORD)
VALUES(?,?,?)";
using(OleDbConnection con = new OleDbConnection(.......))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("p1", OleDbType.VarChar).Value = txtname.Text;
cmd.Parameters.Add("p2", OleDbType.VarChar).Value = txtemail.Text;
cmd.Parameters.Add("p3", OleDbType.VarChar).Value = txtpass.Text ;
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else
{
MessageBox.Show("Success!");
MessageBox.Show("User has been created");
}
}
Form1 login = new Form1();
login.Show();
}
I have also removed the passing of a parameter for the CUSTOMER_ID field. This seems to be a field that is calculated automatically by Oracle (a Sequence?) and thus you don't need to provide a value for it.
Finally an advice. Do not store password in plain text in the database. This is a security risk very seriours. You should read Best way to store passwords in a database
Your CommandText seems wrong. Why do you wrap all values with '%'? And you should pass null as string. Concatination with null does not changes any string value.
I think it should be:
cmd.CommandText = $#"INSERT INTO SYSTEM.CUSTOMER
('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')
VALUES(NULL, {txtname.Text}, {txtemail.Text}, {txtpass.Text})";
I'm new at this. Im making a c# console program that reads sql database via datareader, displays a statement if any row matches the query and updates those rows via sql update query. But I can't figure out how to fix this error. here is my code. help appreciated. thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
namespace emailsend
{
class Program
{
#region Connection String
static private SqlConnection connection = new SqlConnection("Data Source=server;Initial Catalog=dbTrainning;User ID=user;Password=123");
#endregion
static void Main(string[] args)
{
#region SQL Select Unsent Query
string Sql = "SELECT * FROM People where Visits is Null;";
SqlCommand cmd = new SqlCommand(Sql, connection);
#endregion
#region Open DB Connection
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
#endregion
SqlDataReader DR = cmd.ExecuteReader();
#region Try Catch Block
try
{
while (DR.Read())
{
#region Fetching DB data
DateTime TimeStamp = (DateTime)DR["ExceptionDate"];
string VNumber = (string)DR["VisitNumber"];
Console.Write("Total Visits = " +VNumber "\n");
#endregion
DR.Close();
}
cmd = new SqlCommand("UPDATE People SET Visits = '0' WHERE VisitNumber = '" + VNumber + "'", connection); //The name 'VNumber' does not exist in the current context
cmd.ExecuteNonQuery();
}
catch (SqlException exception)
{
Console.Write(exception);
}
finally
{
connection.Close();
}
#endregion
}
}
}
It is because you create VNumber in a while loop and it is not visible outside. try it:
try
{
string VNumber = null; //outside the loop
while (DR.Read())
{
#region Fetching DB data
DateTime TimeStamp = (DateTime)DR["ExceptionDate"];
VNumber = (string)DR["VisitNumber"];
Console.Write("Total Visits = " +VNumber "\n");
#endregion
DR.Close();
}
cmd = new SqlCommand("UPDATE People SET Visits = '0' WHERE VisitNumber = '" + VNumber + "'", connection); //The name 'VNumber' does not exist in the current context
cmd.ExecuteNonQuery();
}