Windows Form App data isn't inserting while connected to DB - c#

Finally got the app to connect to the SQL DB on the server. But now the test data won't insert.
I'm getting no errors
private void BtnUpload_Click(object sender, EventArgs e)
{
btnUpload.Enabled = false;
Application.DoEvents();
UploadFile(txtFTPAddress.Text, txtFilePath.Text, txtUsername.Text, txtPassword.Text);
btnUpload.Enabled = true;
string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (SqlConnection Conn = new SqlConnection(connString))
try
{
Conn.Open();
string insertURL = "insert into modelGEOmodelData (ID, Name, Location, modelGeoURL) values (#ID, #Name, #Location, #modelGeoURL)";
SqlCommand command = new SqlCommand(insertURL, Conn);
string id = "1234";
string name = "pump";
string local = "redford";
command.Parameters.Add(new SqlParameter("#ID", id));
command.Parameters.Add(new SqlParameter("#Name", name));
command.Parameters.Add(new SqlParameter("#Location", local));
command.Parameters.Add(new SqlParameter("#modelGeoURL", FileURLtxt.Text));
Conn.Close();
}
catch
{
}

Related

How do i store data in a service-based database?

I am trying to store the username and password inside a table called 'User' which is inside a service-based database.
Below is code of what i have tried.
private void Btn_register_Click(object sender, RoutedEventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\CUC-SRV-FS02\Studio-StuHome$\13mihailovs.m\Documents\IT_Unit4\IT_Unit4\ITUnit4.mdf;Integrated Security=True");
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into User(Username, Password) " +
"values(#Username, #Password)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#Username", txt_username.Text);
com.Parameters.AddWithValue("#Password", txt_password.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
MessageBox.Show("error has occured");
}
}
currect way for insert into database in Ado.Net:
private readonly SqlConnection _con = new SqlConnection("Data Source=.;Initial
Catalog=dbPhoneBook;Integrated Security=True");
public string Add(string user , string pass)
{
string result = "";
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = _con;
cmd.CommandText = "insert into tbl_login(user,pass)values(#user,#pass)";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
if (_con.State != ConnectionState.Open)
{
_con.Open();
}
cmd.ExecuteNonQuery();
result = "Ok";
cmd.Dispose();
}
catch
{
cmd.Dispose();
result = "NOk";
}
return result;
}
Also check the following
Check out the web site https://www.connectionstrings.com/ link to the database.

I want to insert null in database if i dont choose an image from imageupload control in asp.net

I have a FileUpload control and when I don't insert an image, I want to insert DBNull into the database. So far I have only errors with DBNull.Value. The table allow null for column ImageData.
Here is the code:
protected void button_sign_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
string Image = "~/userimage/" + str.ToString();
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username, #Email, #Password, #ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", Image);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
}
else
{
lblMsg.Text = "Error";
}
}
This should be enough
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? Image: DbNull.Value);
Also refactor your code a little bit:
string image = "";
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
image = "~/userimage/" + str.ToString();
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String connString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? image: DbNull.Value);
con.Open();
cmd.ExecuteNonQuery();
}
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
Don't start your variables with UpperCase letters.
If you set the value of Image at the beginning the rest of the code could stay generic.
protected void button_sign_Click(object sender, EventArgs e)
{
object Image;
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
Image = "~/userimage/" + str.ToString();
}
else {
Image = System.DBNull.Value;
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
using(SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con))
{
// pick the appropriate SqlDbType type for each parameter
cmd.Parameters.Add(new SqlParameter("#Username", SqlDbType.VarChar){Value = name});
cmd.Parameters.Add(new SqlParameter("#Email", SqlDbType.VarChar){Value = email});
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar){Value = pass});
cmd.Parameters.Add(new SqlParameter("#ImageData", SqlDbType.VarChar){Value = Image});
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
Some other notes though
You should specify the Database types using the SqlDbType in your parameters to make sure that the values are translated correctly by the ado.net code.
Wrap you Command in a using block as well
No need to close the connection, the using block will handle that for you.
Do not store passwords in clear text. Instead store a salted hash of the password.

What query syntax should I use for inserting records in an Oracle database?

I'm a beginner and trying to create a simple program in C# for inserting and updating records in an Oracle database. I have managed to successfully connect to the database but I'm getting an exception for my SQL statement which states that (?) symbol is not supported. Why am I getting this exception and how can I fix this?
My code is:
private void btnSave_Click(object sender, EventArgs e)
{
OracleConnection con = null;
try
{
con = new OracleConnection();
string constr = "Data source=XE; User ID=cloudester; Password=cloudester123;";
if (con.State != ConnectionState.Open)
{
try
{
con.ConnectionString = constr;
con.Open();
//MessageBox.Show("Successfull connection");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception caught");
}
}
if (con.State == ConnectionState.Open)
{
string str = "Insert into EMP_DETAIL(EmpId, Name, Age)";
str += "values (?,?,?)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = Text;
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
}
}
catch { ... }
}
You need to use the named parameter for your command
string str = "Insert into EMP_DETAIL(EmpId, Name, Age) values (:EmpId, :Name, :Age)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = str; //cmd.CommandText = Text; not sure why did you use Text here
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
As agent5566 said, and from OracleCommand.Parameters property;
When using named parameters in an SQL statement called by an
OracleCommand of CommandType.Text, you must precede the parameter name
with a colon (:)
Use them like;
using(var con = new OracleConnection(constr))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"Insert into EMP_DETAIL(EmpId, Name, Age)
values (:EmpId, :Name, :Age)";
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
con.Open();
cmd.ExecuteNonQuery();
}
By the way, System.Data.OracleClient has been marked as deprecated in .NET 4 version. You might wanna use Oracle Data Provider for .NET instead.
As an alternative, DataDirect and DevArt also have their own oracle providers for .NET.

Retrieving Hash Password error

I am trying to log on with a username and original password that already stored in the database with a hashed password.
But, when I am trying to log on, I received the message says that value cannot be null on if (salt == null) {
throw new ArgumentNullException("salt");
}
I am using BCrypt.cs for hashing the password in the database. BCrypt.cs
Here is my code for register the user:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
Password.Hashed = BCrypt.HashPassword(this.textBox2.Text, BCrypt.GenerateSalt(12));
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType]) VALUES (#Username, #Password, #UserType)";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = Password.Hashed;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.comboBox1.SelectedItem;
cmd.ExecuteNonQuery();
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
Login _login = new Login();
_login.ShowDialog();
this.Close();
}
}
conn.Close();
}
Here is my code for log on the user:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType] FROM [Member] WHERE [Username] = #Username AND [Password] = #Password";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = BCrypt.CheckPassword(this.textBox2.Text, Password.Hashed);
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
if (dReader.Read())
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
this.Hide();
this.Close();
}
else
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
dReader.Close();
conn.Close();
}
}
}
Here is the password class:
public static string Hashed
{
get;
set;
}
Any help would be appreciated and your answer much appreciated!
Thank you so much.
EDITED:
My database looks like this:
That password was hashed (salt) and my original password that I use for the login is Kaoru. That password was generated from original password, which is Kaoru
Try the following code:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType] FROM [Member] WHERE [Username] = #Username";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
bool isValidPassword = false;
if (dReader.Read())
{
string password = (string)dReader["Password"];
bool isValidPassword = BCrypt.CheckPassword(this.textBox2.Text, password);
if (isValidPassword)
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
this.Hide();
this.Close();
}
}
if (!isValidPassword)
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
}
}
}

SQL Insert Query Using C#

I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}

Categories