Basic inserting data into SQL Server database - c#

I'm a newbie in Visual Studio and I want to make a database system that allows the user to insert, update, delete and search data using a Windows Forms application.
I already watched 3 tutorial how but I'm getting the same error. when I delete my ExecuteNonQuery() call, it doesn't have any error but the data I entered into my textboxes is not inserted into my database. When I put it back I'm getting this kind of error
ERROR:
CODE:
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;
using System.Threading.Tasks;
namespace EaglePlannersDatabase
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Adrian\Documents\EaglePlannersDataBase.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void InsertButton_Click(object sender, EventArgs e)
{
connection.Open();
SqlCommand cmd = new SqlCommand("Insert Into EAGLEPLANNERS(policy number,plan type,renewal date,name,age,address,birthday,email,home/office number,mode of payment,amount) values (#policy number,#plan type,#renewal date,#name,#age,#address,#birthday,#email,#home/office number,#mode of payment,#amount)", connection);
cmd.Parameters.AddWithValue("#policy number", int.Parse(policyNumbertxtbox.Text));
cmd.Parameters.AddWithValue("#plan type", planTypetxtbox.Text);
cmd.Parameters.AddWithValue("#renewal date", int.Parse(renewalDatetxtbox.Text));
cmd.Parameters.AddWithValue("#name", nametxtbox.Text);
cmd.Parameters.AddWithValue("#age", int.Parse(agetxtbox.Text));
cmd.Parameters.AddWithValue("#address", addresstxtbox.Text);
cmd.Parameters.AddWithValue("#birthday", int.Parse(birthdaytxtbox.Text));
cmd.Parameters.AddWithValue("#email", (emailtxtbox.Text));
cmd.Parameters.AddWithValue("#home/office number", int.Parse(homeofficetxtbox.Text));
cmd.Parameters.AddWithValue("#mode of payment", (modeofpaymenttxtbox.Text));
cmd.Parameters.AddWithValue("#amount", int.Parse(amounttxtbox.Text));
cmd.ExecuteNonQuery();
connection.Close();
policyNumbertxtbox.Text = "";
planTypetxtbox.Text = "";
renewalDatetxtbox.Text = "";
nametxtbox.Text = "";
agetxtbox.Text = "";
addresstxtbox.Text = "";
birthdaytxtbox.Text = "";
emailtxtbox.Text = "";
homeofficetxtbox.Text = "";
modeofpaymenttxtbox.Text = "";
amounttxtbox.Text = "";
MessageBox.Show("Record inserted successfully!");
}
}
}

As a newbie, getting the pieces working first, then applying to the user interface I would apply second. I will try to summarize each piece. First your connection itself looked strange as others have pointed out. I would try to first make sure the connection itself works before applying any attempt at sql insert/update/delete going on. So you might try
SqlConnection connection = new SqlConnection(
#"Data Source (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Adrian\Documents\EaglePlannersDataBase.mdf;
Integrated Security=True;
Connect Timeout=30" );
private void TestConnect()
{
if( connection.Open() )
// great, you have a good connection
connection.Close();
else
// message to yourself why a failed connection and fix it...
}
Once you know your connection is good, then on to your sql-insert. Having good column names is important. Dont try to be fancy with human readable with spaces types of column names, just causes headaches. Use simple and direct as others have pointed out in prior comments. Also, when parameterizing, I have tried to always slightly alter the insert/update/delete parameters with a "p" prefix indicating the PARAMETER FOR the column, such as
insert into SomeTable ( oneColumn, secondCol ) values ( #pOneColumn, #pSecondCol )
just to avoid bad confusion. If an error comes out via "oneColumn" vs "pOneColumn" in the message, you KNOW which thing is at fault. The column itself does not work, or the specific parameter/value being supplied.
Next, readability of your SQL statements, especially as they get longer. Use spaces and I typically use a leading "#" before the quoted sql command to allow for line continuations as I edited your previous answer. So the same above insert would be written more like
var cmd = new SqlCommand(
#"insert into SomeTable
( oneColumn,
secondCol
)
values
( #pOneColumn,
#pSecondCol
)", connection );
So if you ever needed to add additional columns (or remove), you can see the paired set of insert columns vs parameters much easier.
Now the testing. Don't try to work off some user-entered values, put in known VALID values so you dont have to worry about user entered values. Get the command to WORK, then pull values from interface later. (continuing from above sample)
cmd.Parameters.AddWithValue("#pOneColumn", 17 );
cmd.Parameters.AddWithValue("#pSecondCol", "some Text");
Then try to execute that and make sure IT works. Once it does, THEN start pulling from your user interface
cmd.Parameters.AddWithValue("#pOneColumn", int.Parse( yourTextControl.Text ));
cmd.Parameters.AddWithValue("#pSecondCol", anotherTextControl.Text );
Find your mistakes BEFORE you let any human interaction get into and screw-up the rest of what you think SHOULD work.
Note, if you make public properties to your view models such as
public int someAge {get; set;}
and then set the bindings of the data entry control in the screen to this someAge property, it will only allow a numeric entry to be entered and will otherwise have a value of zero if someone tries to put in text. Similarly if you are dealing with dates, and if date/time, always use datetime fields for querying purposes vs formatted date as a text field. You will thank yourself in the future when querying for things within date range periods. HTH
Finally,try to avoid using AddWithValue. Instead, properly identify the expected data type as described in the linked article. I just left original context to your code for testing and debug researching purposes.

This would be the possible answer on your question, what I have done here, first I changed your connection string by removing AttachDbFilename attribute, and replace that by adding of Initial Catalog attribute where I set the name of your database.
Next thing, I declared variables where the values from textboxes will be stored, these values of variables will be our parameters, this is not necessary to do, it is just my own style, you can keep as you done.
I have seen also, that you are not using try/catch/finally block and you are closing the connection in the same part of code where you opening the connection, and maybe that is the reason why your values are not being stored into the table, so I decided to round your code within that block. If you don't know what is try/catch/finally block you can read the documentation here . We are opening the connection and do all operations on database in try block, in catch block we are catching all errors that might be caused in our application and in finally we are closing the connection. You will also notice that I created additional check, where I checking the result of ExecuteNonQuery() method, and if result of ExecuteNonQuery method is equals to 1 - records is inserted successfully, otherwise it fails.
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;
using System.Threading.Tasks;
namespace EaglePlannersDatabase
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=EaglePlannersDataBase;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void InsertButton_Click(object sender, EventArgs e)
{
int policyNumber = Convert.ToInt32(policyNumbertxtbox.Text);
string planType = planTypetxtbox.Text;
int renewalDate = Convert.ToInt32(renewalDatetxtbox.Text);
string name = nametxtbox.Text;
int age = Convert.ToInt32(agetxtbox.Text);
string address = addresstxtbox.Text;
int birthday = Convert.ToInt32(birthdaytxtbox.Text);
string email = emailtxtbox.Text;
int homeOfficeNumber = Convert.ToInt32(homeofficetxtbox.Text);
string modeOfPayment = modeofpaymenttxtbox.Text;
int amount = Convert.ToInt32(amounttxtbox.Text);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("Insert Into tbl1 (PolicyNumber,planType,renewalDate,name,age,address,birthday,email,homeOfficeNumber,modeOfPayment,amount) values (#PolicyNumber,#planType,#renewalDate,#name,#age,#address,#birthday,#email,#homeOfficeNumber,#modeOfPayment,#amount)", connection);
cmd.Parameters.AddWithValue("#PolicyNumber",policyNumber);
cmd.Parameters.AddWithValue("#planType",planType);
cmd.Parameters.AddWithValue("#renewalDate",renewalDate);
cmd.Parameters.AddWithValue("#name",name);
cmd.Parameters.AddWithValue("#age",age);
cmd.Parameters.AddWithValue("#address",address);
cmd.Parameters.AddWithValue("#birthday",birthday);
cmd.Parameters.AddWithValue("#email",email);
cmd.Parameters.AddWithValue("#homeOfficeNumber",homeOfficeNumber);
cmd.Parameters.AddWithValue("#modeOfPayment",modeOfPayment);
cmd.Parameters.AddWithValue("#amount",amount);
int result = cmd.ExecuteNonQuery();
if(result == 1)
{
MessageBox.Show("Record Inserted Successfully!");
policyNumbertxtbox.Text = "";
planTypetxtbox.Text = "";
renewalDatetxtbox.Text = "";
nametxtbox.Text = "";
agetxtbox.Text = "";
addresstxtbox.Text = "";
birthdaytxtbox.Text = "";
emailtxtbox.Text = "";
homeofficetxtbox.Text = "";
modeofpaymenttxtbox.Text = "";
amounttxtbox.Text = "";
}
else
{
MessageBox.Show("Something went wrong!");
}
}
catch(SqlException ex)
{
MessageBox.Show("We have found error with operation on database: " + ex.Message);
}
catch(Exception ex)
{
MessageBox.Show("We have found error in your code: " + ex.Message);
}
finally
{
connection.Close();
}
}
}
}

here's my new code
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;
using System.Threading.Tasks;
namespace EaglePlannersDatabase
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Adrian\Documents\EaglePlannersDataBase.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void InsertButton_Click(object sender, EventArgs e)
{
connection.Open();
SqlCommand cmd = new SqlCommand(
#"Insert Into tbl1
( PolicyNumber,
planType,
renewalDate,
name,
age,
address,
birthday,
email,
homeOfficeNumber,
modeOfPayment,
amount )
values
( #PolicyNumber,
#planType,
#renewalDate,
#name,
#age,
#address,
#birthday,
#email,
#homeOfficeNumber,
#modeOfPayment,
#amount )", connection);
cmd.Parameters.AddWithValue("#PolicyNumber", int.Parse(policyNumbertxtbox.Text));
cmd.Parameters.AddWithValue("#planType", planTypetxtbox.Text);
cmd.Parameters.AddWithValue("#renewalDate", int.Parse(renewalDatetxtbox.Text));
cmd.Parameters.AddWithValue("#name", nametxtbox.Text);
cmd.Parameters.AddWithValue("#age", int.Parse(agetxtbox.Text));
cmd.Parameters.AddWithValue("#address", addresstxtbox.Text);
cmd.Parameters.AddWithValue("#birthday", int.Parse(birthdaytxtbox.Text));
cmd.Parameters.AddWithValue("#email", (emailtxtbox.Text));
cmd.Parameters.AddWithValue("#homeOfficeNumber", int.Parse(homeofficetxtbox.Text));
cmd.Parameters.AddWithValue("#modeOfPayment", (modeofpaymenttxtbox.Text));
cmd.Parameters.AddWithValue("#amount", int.Parse(amounttxtbox.Text));
cmd.ExecuteNonQuery();
connection.Close();
policyNumbertxtbox.Text = "";
planTypetxtbox.Text = "";
renewalDatetxtbox.Text = "";
nametxtbox.Text = "";
agetxtbox.Text = "";
addresstxtbox.Text = "";
birthdaytxtbox.Text = "";
emailtxtbox.Text = "";
homeofficetxtbox.Text = "";
modeofpaymenttxtbox.Text = "";
amounttxtbox.Text = "";
MessageBox.Show("Record Inserted Successfully!");
}
}
}
here's my database

Related

SqlException was unhandled in C# - Information into Database Table

I'm new to coding in C# and have looked around but finding it hard to extrapolate an answer for my problem.
I'm currently just trying to get to grips with adding text and selected text from a combobox into a simple database table. However when I try to add the information I get an error of SqlException was unhandled. I've looked at other answers and saw it maybe something to do with adding a connection, which I've tried but it's still not working...
My code and error message as in the image link below but just in case here is my code also,
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.Data.SqlClient;
using System.Windows.Forms;
namespace SavetoDbTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection test = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\Visual Studio 2015\\Projects\\SavetoDbTest\\SavetoDbTest\\Hobbie.mdf;Integrated Security=True"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
}
}
+1 for trying to use parameterized queries! But you're not doing it right :-)
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
This add parameters when the query string doesn't expect them. Probably this is also the cause for the exception you're seeing.
Your query string must look like this:
again.CommandText = "INSERT INTO [Table] Values(#Name, #Hobby)";
Also, TABLE is a reserved word in SQL. So if your table is named Table, you should wrap it in square brackets.
Use this instead of:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection test = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\Visual Studio 2015\\Projects\\SavetoDbTest\\SavetoDbTest\\Hobbie.mdf;Integrated Security=True"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO [TableName] Values(#Name,#Hobby)";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
As mentioned by PaulF it is always a good practise to use Try..Catch block. It will give you the exception message if the code doesn't works for you. Here you go.
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection test = new SqlConnection("YourConnectionStringName"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO Table Values(#Name,#Hobby)";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Check whether it is working or not. Hope atleast it will give you one step ahead result to let you know if any exception arises
Precisely this exception is being thrown because table is a reserved keyword. SQL engine encounters this reserved keyword, when it expects to find a proper name of the table and thus throws an exception. Try specifiying correct table name, because I believe this table name was given just as an example.
Your statement should look a little bit more like this
INSERT INTO MyTable Values ...
Other answers about using parametrized query in incorrect way are also valid.
there are 3 issues in your code.
1) you have reserved keyword for table name, Table
2) SQL query you are building from code is incorrect.
3) You need to specify your command type.
Solution: Change table name to something meaningful, like employeedata or testdata and modify your code according to given below.
again.CommandType = CommandType.Text;
again.CommandText = "INSERT INTO TestData(ColumnName1,ColumnName2) Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");

Escaping commas, colons and single quotes with mySQL in C#

--- THIS IS FOR PERSONAL USE, SO DON'T WORRY ABOUT SQL INJECTION ---
I've been browsing through several tutorials on mySQL escaping for C# but cannot find one that works for me (maybe I'm just using it incorrectly)
I'm trying to insert data into a mySQL database.
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace HASHSITE
{
class Program
{
static void Main(string[] args)
{
bool success;
int done = 0;
string path = #"C:\Users\somePC\Documents\someFolder\somefile.txt";
string server = "someIP";
string database = "some_db";
string uid = "some_dbu";
string password = "pass";
string connectionstring = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + uid + ";PASSWORD=" + password + ";";
using (var connection = new MySqlConnection(connectionstring))
{
connection.Open();
using (var cmd = new MySqlCommand("INSERT INTO databases(data) VALUES(#name)", connection))
{
var parameter = cmd.Parameters.Add("#name", MySqlDbType.LongText);
foreach(string line in File.ReadLines(path))
{
success = false;
while (!success)
{
parameter.Value = line;
cmd.ExecuteNonQuery(); //ERROR IS HERE
success = true;
}
done += 1;
Console.WriteLine("\n" + done);
}
}
}
}
}
}
I need to escape commas present in the string line which is
name,name#name.com
ERROR:
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'databases(data) VALUES
Don't try to escape anything - just use parameterized SQL. You may not care about SQL injection attacks now, but you will at some point... and by using parameterized SQL for your values, you'll remove both the escaping and injection attack issues. Oh, and you'll reduce type conversion concerns. And make your SQL more readable. It's a win all round.
Note that DATABASES is a reserved word, so you do need to quote that - or change the name of your table to something which isn't going to be as awkward.
// TODO: Specify the column name as well, for clarity if nothing else
cmd.CommandText = "INSERT INTO 'databases' VALUES(#name)";
// Adjust for your actual type
cmd.Parameters.Add("#name", MySqlDbType.LongText).Value = line;
...
Note that you only want to call cmd.Parameters.Add once though, so in your case with a loop you'd probably want to call that (and set the command text) outside the loop, then just set the Value property inside the loop.
When in doubt, get in the habit of doing the right thing early, rather than assuming you'll find the time to undo your bad habits later on.
While you're at it, now would be a good time to start using using statements... and you can reuse pretty much everything, just changing the parameter value on each iteration:
using (var connection = new MySqlConnection(...))
{
connection.Open();
using (var command = new MySqlCommand("INSERT INTO 'databases' VALUES(#name)", connection)
{
var parameter = command.Parameters.Add("#name", MySqlDbType.LongText);
foreach (...)
{
parameter.Value = line;
command.ExecuteNonQuery();
}
}
}

Getting Exception error saying: Syntax error (missing operator) in query expression

I am working on a Database app in c# that connects to a Microsoft Access database. Now I had it working where when I would click on Save it would say the data was entered successfully, but I found out that it actually wasn't entering the data into the Database.
So with help from the fine folks here at stackoverflow I was able to find out what I needed to do to get it to work, however I am now getting an unhandled exception saying the following:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error (missing operator) in query expression '#[Guest First Name]'.
I'm curious as to where the problem is. This exception is thrown when it reaches the com.ExecuteNonQuery(); line of the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using System.Data;
using System.ComponentModel;
namespace ParkingDatabase
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
using (OleDbConnection DBConnect = new OleDbConnection())
{
DBConnect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\bkoso\documents\visual studio 2015\Projects\ParkingDatabase\ParkingDatabase\ParkingData.accdb";
using (OleDbCommand com = new OleDbCommand("INSERT INTO [Guest Info]([Guest First Name], [Guest Last Name], [Room Number], [Departure Date], [Return Date], [Vehicle Colour], [Vehicle Make], [Plate Number], [Contact First Name], [Contact Last Name], [Contact Number], [Contact Email], [Tag Number]) Values(#[Guest First Name], #[Guest Last Name], #[Room Number], #[Departure Date], #[Return Date], #[Vehicle Colour], #[Vehicle Make], #[Plate Number], #[Contact First Name], #[Contact Last Name], #[Contact Email], #[Contact Email], #[Tag Number])", DBConnect))
//the section below was recently updated
{
com.Parameters.AddWithValue("#GuestFirstName", txtBxGstFName.Text);
com.Parameters.AddWithValue("#GuestLastName", txtBxGstLName.Text);
com.Parameters.AddWithValue("#RoomNumber", txtBxRm.Text);
com.Parameters.AddWithValue("#DepartureDate", txtBxDDate.Text);
com.Parameters.AddWithValue("#ReturnDate", txtBxRDate.Text);
com.Parameters.AddWithValue("#VehicleColour", txtBxVColour.Text);
com.Parameters.AddWithValue("#VehicleMake", txtBxVMake.Text);
com.Parameters.AddWithValue("#PlateNumber", txtBxPlate.Text);
com.Parameters.AddWithValue("#ContactFirstName", txtBxContactFName.Text);
com.Parameters.AddWithValue("#ContactLastName", txtBxContactLName.Text);
com.Parameters.AddWithValue("#ContactNumber", txtBxPhone.Text);
com.Parameters.AddWithValue("#ContactEmail", txtBxEmail.Text);
com.Parameters.AddWithValue("#TagNumber", txtBxTag.Text);
DBConnect.Open();
com.ExecuteNonQuery();
DBConnect.Close();
}
if (DBConnect.State == ConnectionState.Open)
{
//com.ExecuteNonQuery();
MessageBox.Show("Guest Information Saved Successfully");
txtBxGstFName.Text = "";
txtBxGstLName.Text = "";
txtBxRm.Text = "";
txtBxDDate.Text = "";
txtBxRDate.Text = "";
txtBxVColour.Text = "";
txtBxVMake.Text = "";
txtBxPlate.Text = "";
txtBxContactFName.Text = "";
txtBxContactLName.Text = "";
txtBxPhone.Text = "";
txtBxEmail.Text = "";
txtBxTag.Text = "";
}
}
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
txtBxGstFName.Text = "";
txtBxGstLName.Text = "";
txtBxRm.Text = "";
txtBxDDate.Text = "";
txtBxRDate.Text = "";
txtBxVColour.Text = "";
txtBxVMake.Text = "";
txtBxPlate.Text = "";
txtBxContactFName.Text = "";
txtBxContactLName.Text = "";
txtBxPhone.Text = "";
txtBxEmail.Text = "";
txtBxTag.Text = "";
}
private void btnView_Click(object sender, RoutedEventArgs e)
{
}
private void btnSame_Click(object sender, RoutedEventArgs e)
{
}
private void txtBoxGuestFirstName_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
}
}
}
The problem stems from your parameters, they're declared in the following manner:
#[Guest Name Here]
The # is correct, since it represents your parameter however the bracket is a huge no, no. The bracket's symbolize a Column Name in the database, which could partially be the cause of your issue. Couple that with the spaces, that error is more than likely going to fail.
You should have your parameter in the following format:
#GuestNameHere
Let me know if that resolves your problem. Also, I noticed that you open up your connection, below your parameters, add it above. Structured more like:
private const string dbConnection = "Provider=Microsoft.ACE.OLEDB.12.0;...";
private const string query = "INSERT INTO...";
using((OleDbConnection connection = new OleDbConnection(dbConnection))
using(OleDbCommand command = new OleDbCommand(query, connection))
{
connection.Open();
// Parameter(s) here
command.ExecuteNonQuery();
// Any other logic here.
}
So about the above snippet, the dbConnection would be a readonly so it could access the data from your config. This will make it flexible, if your database changes, you change it in one location rather than many.
The query parameter is similar, it will allow you to hold a const on the page, with all your queries in a single location with ease of access to change without multiple query changes.
Also note, when you utilize the using it implements IDispose. So once the application exits the using block, any value will become out of scope, so it will close your connection.
You should denote the connection to be open towards the top, it is easier to read and will ensure the connection is open before your attempt to manipulate the query.
Since you noted your struggling with dbConnection and query I partially filled in, to indicate location you would have to place full content.
Update:
I also noticed that your query doesn't reflect the changes, you need to ensure the column is indeed present, and in the following format:
[GuestName]
Not in your format, [Guest Name]. Also the sample applies for the inserted values, those values are the parameters they both need to match.

removing form from c# code?

I'm extremely new to C# and programming anything except for SQL. I've gotten the below code to happen on a Form and on a button click. If I wanted to just make this run on open, how would I do that? I'm very new to C# as you can tell (just started today learning it but its pretty exciting!)
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 Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace OraTrigger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT cast(Count(*) as varchar(20)) as trig FROM ZDMSN.TRIGGER_TEST";
//cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
int cnt;
if (int.TryParse(dr.GetString(0), out cnt))
{
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
}
}
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
conn.Dispose();
}
}
}
If you need to run your code as a scheduled task then a command line application is more suitable.
Just create a new project and select Console Application.
Then move all of your button click code inside the Main method written for you by the Visual Studio IDE.
Rembember to set the references to the Oracle ODP.NET library and import the relevant using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand("SELECT Count(*) as trig FROM ZDMSN.TRIGGER_TEST", conn))
{
conn.Open();
int cnt = (int)cmd.ExecuteScalar();
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
cmd.ExecuteNonQuery();
}
}
}
}
}
I have also revised your code to get a single value from the database. For this case is enough to use the Command.ExecuteScalar method that returns the first column of the first row obtained from your sql command text. Because the count(*) should Always return a single row you could easily cast the return value of ExecuteScalar to your record count variable.
EDIT I have added the logic to TRUNCATE the table involved. Please pay attention that you should use the code provided here. Your code will probably fail because you have an open DataReader and when a DataReader is open you cannot execute other commands (This is true for SqlServer without Multiple Active Result Sets enabled, I really don't know if this rules applies also to the Oracle NET Provider)
Subscribe to Shown or Load event of form and move your code to that event handler.
Form.Shown Event Occurs whenever the form is first displayed.
Form.Load Event Occurs before a form is displayed for the first time.
Also I suggest to extract your code to some Data Access related class, or at least to separate method. And call that method from event handler.

stored procedure not getting parameter

Hi I have a stored procedure and a connection to the database. I have other similar code on my website that works just fine but for the life of me I cannot get this to work. I want the username of the person logged in to be passed as a parameter. I can get it stored in a session variable.
I wasnt sure how to transfer it from the session variable to the parameter so I put it into a label and sent it that way. It shows that it is getting that far but everytime I just get the message 'nothing found'
I have checked the stored procedure and that seems fine to me. Below is the code and stored procedure! please help!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class RescueOnlyPages_EditRescueDetails : System.Web.UI.Page
{
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser user;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
user = Membership.GetUser(User.Identity.Name);
Session["user"] = user;
}
}
catch (Exception ex)
{
string msg = ex.Message;
//Log error here
// We have set theme in web.config to Neutral so if there is
// an error with setting themes, an incorrect theme wont be displayed to a customer
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["user"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#user", userLabel.Text.Trim());
}
try
{
MyConnection.Open();
command.CommandType = CommandType.StoredProcedure;
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
stored procedure
ALTER PROC [dbo].[sp_EditRescueDetails]
(
#user nvarchar(50)
)
AS
BEGIN
SELECT [PostalAddress], [Telephone_No], [Website], [Email]
FROM [RescueDetails]
Where [UserName] = #user
End
EDIT *
If I change the stored procedure and delete the
' Where [UserName] = #user '
line it brings in every user detail without any problem so I think it maybe something with this line or the
command.Parameters.AddWithValue("#user", userLabel.Text.Trim());
line that is causing me the problems
Try setting
command.CommandType = CommandType.StoredProcedure;
before
MyConnection.Open();
Also don't call myDataReader.Read(); if you are going to set the myDataReader as the data source for gridview. That will make it skip a row and if result has only one row then the grid will display nothing.
When adding command parameters of text type (varchar, nvarchar) ADO.NET works best when you supply the length of the text value.
Try adding the parameter and then setting the length property and then assigning the value property, rather than using AddWithValue.

Categories

Resources