exact command for storing in the oracle table - c#

This is for a website in C#,Visual Studio 2010.
I've created a form with many textboxes, a date picker, dropdownlist, etc.
I've created a table in sqlplus with the columns with necessary types(varchar, number, date).
When I click the submit button in my form, I want to store the data in the table I've created.
Just to make it simpler for you guys, assume I have 3 text boxes
(name(text), id, date(i've printed the date in the text box as string)).
When I click submit it should fill the table with these data.
Im struggling to get the OracleCommand to execute this.
cmd = new OracleCommand(______, con);
If there is any other way I can do this by manipulating the types also its welcome :)

The insert syntax for oracle commands generally follows the pattern;
string query = #"INSERT INTO SOME_TABLE VALUES (SOME_COLUMN_1 = :SomeParam1,SOME_COLUMN_2 = :SomeParam2 )";
OracleCommand command = new OracleCommand(query, connection) { CommandType = CommandType.Text };
command.Parameters.Add(":SomeParam1", OracleDbType.Varchar2).Value = "Your Val 1";
command.Parameters.Add(":SomeParam2", OracleDbType.Varchar2).Value = "Your Val 2";
connection.ExecuteNonQuery();
See more reference examples here;
Using Named Parameters with Oracle ODP.NET

Related

Issue while showing result of a query from database to DataGridView

working with an assignment here i am able to view all data from database to grid view but the data appears to be unsorted and it displays all data i only want to display the result of a query in the DataGridView the code i have tried is :
private void btnmeritbsit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dbpath);
string query = "select Applicant_no,A_Name,Father_Name,T_Matric,O_Matric,M_Percentage,T_Inter ,O_Inter ,I_Percentage from applicantinfo order by I_Percentage desc";
con.Open();
dataGridView1.ColumnCount = sdr.FieldCount;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
dataGridView1.Rows.Add(sdr["Applicant_no"], sdr["A_Name"], sdr["Father_Name"], sdr["T_Matric"], sdr["O_Matric"], sdr["M_Percentage"], sdr["T_Inter"], sdr["O_Inter"], sdr["I_Percentage"]);
}
con.Close();
}
i was getting the whole values through datatable and dataAdapter but nothing works !!stuck!!
// DataTable dtbl = new DataTable();
// sda.Fill(dtbl);
// dataGridView1.DataSource = dtbl;
What I wrote in the other answer, in pictures. This is using a VB app, but it doesn't matter because the steps are the same and you're not actually going to be writing much more than one line of code
Right click project, add new dataset
Right click surface, add tableadapter
Add a connection string, Next. Name it, Next
Add a query that selects all from your table, WHERE (id column) = #id
Rename the methods to add "ByID". It will be obvious why later. Finish:
Right click table adapter, Add Query
Proceed through choosing "Select that returns rows" and entering a query that seeks users by last name:
Give good names to the new methods. Finish. Save:
Go to the forms designer, make sure Data Sources tool panel is showing (View Menu)
Drag the Users grid node from Data Sources onto the form
It has pre-made a textbox for the ID, because that's the first query in the tableadapter. We'll change it to lastname. Click the button, change its name, change the text it shows. Always make sure your control names are up to date and relevant.
You can see I changed the label too, and I also changed the name of the textbox (you can't see it) and I changed the name of everything in the tray under the designer, so it starts with underscore:
I do this because VB is case insensitive and calling variable the same name as their type is a bad idea in any language, and makes intellisense confusing in VB. You don't have to add the leading underscores in C#. It's enough to discriminate on case alone, though arguably not always wise:
Now we need to change the code. Double click the FillBy button. It goes to code. Maybe you have some code already, maybe not. Make sure the code fills the table using the relevant input. This is the only part of the process that really requires you to think about what you're doing and what your variables are called (they may be different to mine)
The code probably defaulted to saying
_usersTableAdapter.FillByID(_myDataSet.Users, new Guid(_lastNameToolStripTextBox.Text));
Because it used to be set up for you to type an id (guid or int, my db has a guid) in that box but we have changed it for lastname. So we need to change the FillByID (and now you see why we give them sensible names, not FillBy1 and FillBy2) so it's FillByLastName, and we need to change the code so we pass a string lastname, not a guid ID
_usersTableAdapter.FillByLastName(_myDataSet.Users, _lastNameToolStripTextBox.Text);
That's the only code you have to write. Remember I named my things on the form using leading underscores, so my code has leading underscores. If you dont rename your things, your code won't have leading underscores
Now run the app:
Look at all those John Smiths! They are different users, of course - the ID is different for every one. You can even write new details in here and press save to update the db..
From one line of code! :)
this works perfectly fine just after a few changes :)
private void btnmeritbscs_Click(object sender, EventArgs e)
{
string dbpath = #"Data Source=DESKTOP-UMA0VFO;Initial Catalog=ApplicationForm;Integrated Security=True";
SqlConnection con = new SqlConnection(dbpath);
string query = "select prgstatus,Applicant_no,A_Name,Father_Name,T_Matric,O_Matric,M_Percentage,T_Inter ,O_Inter ,I_Percentage from applicantinfo where prgstatus like 'bscs' order by I_Percentage desc";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dataGridView1.ColumnCount = sdr.FieldCount;
while (sdr.Read())
{
dataGridView1.Rows.Add(sdr["prgstatus"], sdr["Applicant_no"], sdr["A_Name"], sdr["Father_Name"], sdr["T_Matric"], sdr["O_Matric"], sdr["M_Percentage"], sdr["T_Inter"], sdr["O_Inter"], sdr["I_Percentage"]);
}
con.Close();
}

Inserting bool into SQL database, c#

I am making a C# client-server application for my college class.
I have an MS Access database with a table Package, it has some values like 'name', 'dateFrom', 'dateTo', and 2 values called 'internet' and 'telephone' which are YES/NO type
In the program I made a class Package and set internet and telephone as bool type of data. Firstly, is this correct? If value is set as YES/NO in MS Access, am I supposed to set it as bool in C#? this seems logical to me..
Secondly, when I enter SQL command for inserting these values I get an error, I don't know how to send bool values to database
Here is my code
command.CommandText = "Insert into Package values ("+p.PackageID+", '"+ p.Name+"', '"+p.DateFrom.ToString()+"', '"+p.DateTo.ToString()+"', "+Convert.ToBoolean(p.Internet.ToString())+", "+Convert.ToBoolean(p.Telephone.ToString())+")";
command.ExecuteNonQuery();
I tried a lot of things, and this was my last attempt of converting values to be able to insert them.. but it doesn't work..
I always get System.InvalidOperationException
For various reasons, you SHOULD NOT USE string concatenation on SQL statements. Use parameters. Try like:
command.CommandText = "Insert into Package values (#param1,#param2#param3,#param4,#param5,#param6)";
command.Parameters.Add("#param1", OleDbType.Integer).Value = p.PackageID;
command.Parameters.Add("#param2", OleDbType.VarWChar).Value = p.Name;
command.Parameters.Add("#param3", OleDbType.Date).Value = p.DateFrom;
command.Parameters.Add("#param4", OleDbType.Date).Value = p.DateTo;
command.Parameters.Add("#param5", OleDbType.Boolean).Value = bool.Parse(p.Internet.ToString());
command.Parameters.Add("#param6", OleDbType.Boolean).Value = bool.Parse(p.Telephone.ToString());
command.ExecuteNonQuery();

DataGridView not reflecting change on database

My C# Datagridview does not show updated data.
This is a Winform, c# application using SQLite. When my form is open, it is showing the data the way it looked before I updated a column on two separate rows using DB Browser for SQLite. In the DB Browser when I execute this SQL: SELECT * FROM SPEAKERS, I see a 10 and a 13 in the column I changed (they used to be a 0 and a 2. This column is defined as an INTEGER.
When I open that particular form, it shows the data in that column as a 0 and a 2. Further down the grid I see 12's and 13's, etc. so it's not a formatting issue on the column. On this form I have an hCDataset, an speakersBindingSource and a speakersTableAdapter. When I right-click on the speakersTableAdapter and choose "Preview Data", it shows the hierarchy of the HCDataSet and the Speakers table under that with the selected object: HCDataSet.Speakers.Fill.Getdata() method. When I hit the Preview button, the data looks exactly like on my datagrid.
Believe me, I've rebooted, closed everything, gone back into the DB Browser for SQLite and every time it opens up with the 10 and 13 in those columns, but it never shows up in the grid on my form with those new updated values in that column.
I thought I could take screenshots, but apparently not. I can paste my screenshots into Paint and they look fine, but apparently when I copy from there and hit CTRL-G in this editor, they don't show up in this document. Maybe I don't have high enough permissions or something.
I've read on other posts that people are having issues updating from the grid and not seeing the updates on the database. I'm kind of having the opposite problem where I update the database, but for some reason the grid isn't showing it.
I've added the code where I'm showing you my connect methods and the code to query the database. When I get to the 3rd row, it display the correct '10' from the RANK column!!
public static SQLiteCommand GetSqliteCommand()
{
SQLiteConnection conn = GetSqliteConnection();
return conn.CreateCommand();
}
public static SQLiteConnection GetSqliteConnection()
{
string dbPath = Path.Combine(Environment.CurrentDirectory, "hc.db");
string connectionString = string.Format("Data Source={0};foreign keys=true", dbPath);
SQLiteConnection conn = new SQLiteConnection(connectionString);
conn.Open();
return conn;
}
//Now my code snippet to read the database and this DOES return the updated column!
GetLastUpdateSql = "SELECT * FROM SPEAKERS ORDER BY ID";
cmd.CommandText = GetLastUpdateSql;
cmd.ExecuteNonQuery();
SQLiteDataReader reader;
reader = cmd.ExecuteReader();
int int1, int2, int3, int4, int5;
string fn, ln;
while (reader.Read())
{
fn = reader["FIRST_NAME"].ToString();
ln = reader["LAST_NAME"].ToString();
int1 = Convert.ToInt32(reader["ID"]);
int2 = Convert.ToInt32(reader["TYPE"]);
int3 = Convert.ToInt32(reader["WARD"]);
int4 = Convert.ToInt32(reader["RANK"]);
int5 = Convert.ToInt32(reader["ACTIVE"]);
}

C# ComboBox Select Error: "Incorrect Syntax Near '.'"

Note: my office doesn't allow me to view YouTube and several other sites that probably have the answer to this question on them (they are blocked), which is why Googling the answer hasn't yielded results.
ComboBox code reference: found here
On my C# Form, I have filled a ComboBox with tables from a database (see below code), which returns the appropriate values and functions correctly:
public Form1()
{
InitializeComponent();
// Connection
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "CONNECTION STRING" // shortened for security and convenience
// Fill ComboBox with SQL Values
conn.Open();
SqlCommand cmbTables = new SqlCommand("SELECT name FROM sys.tables", conn);
SqlDataReader read = cmbTables.ExecuteReader();
DataTable cmbData = new DataTable();
cmbData.Columns.Add("name", typeof(string));
cmbData.Load(read);
cmb1.DisplayMember = "name";
cmb1.DataSource = cmbData;
conn.Close();
}
After the ComboBox loads the tables (which works), the application then selects a table and clicks a button that loads the table, which is selected. This is where the code errors:
private void button1_Click(object sender, EventArgs e)
{
using (var connection = Utilities.GetConnection())
{
string table = Convert.ToString(txt1.Text);
string cmb1Value = Convert.ToString(cmb1.SelectedItem);
// Stored Procedure
SqlCommand select = new SqlCommand("EXECUTE STOREDPROCEDURE" + cmb1Value, connection); // shortened for security and convenience
select.Parameters.Add(new SqlParameter(cmb1Value, table));
// Data View
SqlDataAdapter ad= new SqlDataAdapter(select);
ad.SelectCommand = select;
DataTable dt = new DataTable();
ad.Fill(dt); // this generates the error "Incorrect Syntax Near '.'"
BindingSource b = new BindingSource();
b.DataSource = dt;
dGrid.DataSource = b;
ad.Update(dt);
connection.Close();
}
}
Even though the ComboBox loads the appropriate values, from the above code, I may be missing something which attaches those values to the SELECT stored procedure (all it does is call SELECT statement through a variable passed to it). The error, "Incorrect Syntax Near '.'" looks like a SQL Server error that I've seen, but can't remember how I generate it (this is how I usually troubeshoot where the TSQL code went wrong).\
Stored Procedure Related code:
C#:
SqlCommand select = new SqlCommand("EXECUTE STOREDPROCEDURE " + cmb1Value, connection);
TSQL:
CREATE PROCEDURE [STOREDPROCEDURE]
#TableName VARCHAR(250)
AS
BEGIN
DECLARE #sql NVARCHAR(MAX)
SET #sql = N'SELECT TOP 100 *
FROM ' + #TableName
EXECUTE(#sql)
END
-- Note this works in SSMS without a problem.
The above code is incorrect, and when I tweak the TSQL code, I generate similar errors, telling me that somewhere I am missing a conversion, or another variable because SQL Server isn't seeing these table values returned by the SELECT (first block of code). I can ascertain this because I have a second ComboBox that uses similar code EXCEPT that I populated the ComboBox with manual values, and it connects to the tables in the database with no error. So, the ComboBox, which grabs values from the database, that you see above, does not function correctly.
For instance, if I only add the below line of code to the code, I receive an error that it can't find the database "EXECUTE STOREDPROCEDURE System'
select.CommandType = CommandType.StoredProcedure;
However, System isn't a part of anything, so where did that come from? It never errored with this code on the manual ComboBox, as it had no trouble finding the database (using the same connection string, server and database!).
If I try to use a TSQL parameter, such as:
SqlCommand select = new SqlCommand("EXECUTE stp_ReturnTable #p", scon);
select.Parameters.Add(new SqlParameter("#p", cmb1Value));
Suddenly, it can't find the stored procedure. Again, the connection strings are identical for the manual ComboBox and the dynamic ComboBox.
I think the code behind the dynamic ComboBox is wrong. When I'm out of the office, I'll review some videos with detailed demonstrations on how to create a dynamic ComboBox from a database and I have a hunch that a system object is in the way (based on the System error, which exists nowhere in my code, as well as it suddenly being unable to find the database or procedure).
The missing key point in your code is the CommandType.
Without the proper set of this property the default is CommandText and thus the Framework expects a statement that starts with SELECT/INSERT/UPDATE/DELETE etc....
using (var connection = Utilities.GetConnection())
{
string table = Convert.ToString(txt1.Text);
string cmb1Value = Convert.ToString(cmb1.SelectedItem);
// Stored Procedure
SqlCommand select = new SqlCommand("STOREDPROCEDURE", connection);
select.Parameters.Add(new SqlParameter("#TableName", cmb1Value));
// That's the key to let ADO.NET accept the previous CommandText as valid.
// If you omit this the CommandText is assumed to be a SELECT/UPDATE/DELETE etc..
select.CommandType = CommandType.StoredProcedure;
// Data View
SqlDataAdapter ad= new SqlDataAdapter(select);
DataTable dt = new DataTable();
ad.Fill(dt);
BindingSource b = new BindingSource();
b.DataSource = dt;
dGrid.DataSource = b;
}
EDIT Having seen the code of the SP then you could simply set the SqlParameter name to the constant #TableName and pass the value extracted from the combobox as the value to be used inside the SP
EDIT I have looked again at your code and I suspect that the culprit is the line
string cmb1Value = Convert.ToString(cmb1.SelectedItem);
Looking at how you have filled your combo, this line, doesn't return the tablename as you expect, but the generic string System.Data.DataRowView because the DataSource of the combo is a DataTable and not a string collection. You should try to change that line in this way
DataRowView rw = cmb1.SelectedItem as DataRowView;
if(rw != null)
{
string cmbValue1 = rw["name"].ToString();
....
And yes, your code should work also without the CommandType.StoredProcedure line because the text EXECUTE sp param is recognized as a valid sql commandtext (but why do you use it when a direct call to the storedprocedure could be optimized for reuse?)

textbox search like in google

I am using C#.net Windows form , and I need to create a search textbox which will display combo box values (similar to google search); The values displayed in the combo box will be values from the SQL 2005 database (example the user is searching on FirstName, the combobox will display all firstnames, which get filtered as the user types in more letters.... if user is searching on LastName, the combo box displays all LastName values in the database.. etc)
when I am doing the above task
I have written the sql query like this
SELECT distinct(person_Firstname+''+person_Lastname)
AS
name FROM persondetails
WHERE name Like '%'+#name+'%'
when I am executing this query it gives error like this --- must declare a scalar varaible
my aim is when i am entering first letter in textbox it will display all names starting with that letter like in google...
can any one correct this ....
private void tbautocomplete_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection(#"Data Source=88888;Initial Catalog=contrynames;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT distinct(person_Firstname+''+person_Lastname) AS name FROM persondetails WHERE name Like '%'+#name+'%'";
con.Open();
SqlDataReader rea = cmd.ExecuteReader();
if (rea.HasRows == true)
{
while (rea.Read())
namecollection.Add(rea["name"].ToString());
}
rea.Close();
tbautocomplete.AutoCompleteMode = AutoCompleteMode.Suggest;
tbautocomplete.AutoCompleteSource = AutoCompleteSource.CustomSource;
tbautocomplete.AutoCompleteCustomSource = namecollection;
It sounds like you're trying to build an AutoComplete feature in your app. You're only missing the parameter on your SqlCommand. Try this:
string searchFor = "%" + txtName.Text + "%"; //the string the user entered.
cmd.CommandText = #"SELECT distinct(person_Firstname+''+person_Lastname) AS name
FROM persondetails
WHERE person_Lastname Like #name
OR person_Firstname LIKE #name";
cmd.Parameters.AddWithValue("#name", searchFor);
Your WHERE clause must use the column name in your table. It sounds as if you want to match either the first or last name columns with your search token.
WHERE person_Lastname LIKE #name
OR person_Firstname LIKE #name
The functionality you're looking for is called AutoComplete. I'm not familiar with an AutoComplete control in Windows forms, but if there isn't a built in one, there will certainly be third-party controls that do this.
The AutoComplete control will likely provide an event callback where you can put your SQL query to provide the possible completions.
As for your SQL error, it looks like it might be an issue with column names, but it is difficult to tell without your schema.
Edit:
I see you're using an AutoComplete contol already. The problem in your SQL is that your #name parameter is in your query, but you haven't added the parameter to the cmd object, so it doesn't know what value to put there.

Categories

Resources