I'm trying to learn some C#.net. I'm just trying to expose the AdventureWorks database included in my C# class via a web interface. Here's the setup:
I've got a DropDownList in on my ASPX page with an id of tableNameDropDown. It gets populated on Page_Load like this:
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
String table_names_sql = "select Name from sysobjects where type='u' ORDER BY name";
SqlCommand cmd = new SqlCommand(table_names_sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tableNameDropDown.Items.Add(reader[0].ToString());
}
conn.Close();
tableNameDropDown.AutoPostBack = true;
}
And that works just fine, I get a nice long list of the tables in the DB. When someone selects a table from the list, I want to display that table in a GridView control with an id of grid. This is what I've got:
protected void tableNameDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dataSet = new DataSet();
String tableName = columnNameDropDown.SelectedItem.ToString();
String table_sql = String.Format("SELECT * FROM {0};", tableName);
SqlDataAdapter adapter = new SqlDataAdapter(table_sql, conn);
adapter.Fill(dataSet, tableName);
grid.DataSource = dataSet;
grid.DataMember = tableName;
}
When I debug the page, I get an error on the adapter.Fill(dataSet, tableName); line: SqlException: Inlvalid object name '{tableName}'.
The tables in the DB are the following:
dbo.AWBuildVersion
.... more dbo. tables
HumanResources.Department
HumanResources.Employee
.... more HumanResources tables
Person.Address
Person.AddressType
.... more Person tables
... Other prefixes are "Pdoduction, Purchasing, Sales"
There are probably ~50+ tables, and I get all their names (without the prefixes) into my DropDownList no problem, but I can't seem to query them.
Any ideas?
You've already answered yourself: you need to use also the prefix in the select statement you're executing, like
Select * From Person.Address
Beside that you should not use the sysobject tables, from SQL Server 2005 you have system views that helps you, so you can write a better statement to select tables:
select * From INFORMATION_SCHEMA.TABLES
Check also this article.
Regards
Massimo
Related
I am trying to query from multiple tables in one query.
Although my code is working for one table, I don't know how to search in the second table too.
using (DataTable dt = new DataTable("Uniclass2015_EF_v1_12; Uniclass2015_En_v1_26"))
{
using (SqlCommand cmd = new SqlCommand (" select *from Uniclass2015_En_v1_26 where title like #Title; select *from Uniclass2015_EF_v1_12 where title like #Title", conn))
{
cmd.Parameters.AddWithValue("code", txtSearch.Text);
cmd.Parameters.AddWithValue("Title", string.Format("%{0}%", txtSearch.Text));
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
conn.Close();
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter
BtnSearch.PerformClick();
}
I tried to add a second table to my original code, but however when I type in the search box my query I receive a blank answer.
looks like you're wanting to use the UNION operator in SQL:
https://www.w3schools.com/sql/sql_union.asp
SELECT * FROM Uniclass2015_En_v1_26 WHERE title LIKE #Title UNION
SELECT * FROM Uniclass2015_EF_v1_12 WHERE title LIKE #Title
This of course assumes the columns of the two tables are the same. If you only need specific columns from each, just select those columns.
Also, I don't see where you're using that code parameter you're adding
I'm working with a school project where we are supposed to build a simple booking system that utilizes SQL database. Used language is C# and environment Visual Studio Community 2017. I'm trying to build a function where user selects a row from dataGridView1 and clicks 'Add new invoice button'. The booking_id is extracted from dataGridView1 and passed to Form2 where booking-related data is searched with booking_id. This data is then presented in dataGridView2 which lists all services included in the one user-specified booking.
Database contains three relevant tables; Booking, Service and BoughServices.
Booking contains column booking_id (INT)
Services contains columns service_id (INT), name (VARCHAR) and price (INT)
BoughtServices, contains columns Booking.booking_id (INT),
Service.service_id (INT) and amount (INT)
Code on Form1:
// Establish a class for data.
public static class DataToForm2
{
public static int booking_id;
}
// User clicks button 'Add new invoice'.
private void button_CreateInvoice_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
//Note: CurrentRow.Cells[0] contains booking_id.
DataToForm2.booking_id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
f2.Show();
}
Code on Form2:
private void Form2_Load(object sender, EventArgs e)
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
// Set SQL query string.
string query = "SELECT Service.name, Services.price, BoughtServices.amount " +
"FROM Service " +
"INNER JOIN Service.service_id ON BoughtServices.service_id " +
"INNER JOIN Bookings ON Bookings.booking_id = BoughtServices.booking_id " +
"WHERE " +
"Booking.booking_id = #booking_id";
SqlCommand command = new SqlCommand(query, connection);
// Set query parameters.
command.Parameters.Add("#booking_id", SqlDbType.Int).Value = Form1.DataToForm2.booking_id;
// Run SQL query
var dataAdapter = new SqlDataAdapter(query, connection);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView2.DataSource = ds.Tables[0];
}
}
However, this approach is non-functional and crashes with an error System.Data.SqlClient.SqlException: Must declare the scalar variable "#booking_id. I have spent an increasing number of hours to figure this out and find solution from tutorials but so far they all have failed. Interestigly, everything is working just fine when I add booking_id directly to SQL statement. In otherwords, WHERE Booking.booking_id = 2 works like a charm.
Could someone help me and propose how I should format my code so that I am able to perform desired actions? Thank you in advance!
Almost right. The only problem is the SqlDataAdapter that receives the sql string and not the command where you have defined the parameter. Just change
// Run SQL query
var dataAdapter = new SqlDataAdapter(command);
As you can see there is a SqlDataAdapter's constructor that receives a SqlCommand where you could define parameters and set the connection.
You're using the parameterized SQL query incorrectly. It functions more like string.Replace than an assignment. Try
command.Parameters.Add("#booking_id",
Form1.DataToForm2.booking_id);
I have an access database that I am manipulating with C#.
I have connected to it, retrieved a data-set from it and can add rows to a table. Now I am trying to clear a table and I am unable to get it to work.
I have tried TRUNCATE TABLE table_name but that throws an exception saying that I must use either DELETE, INSERT, PROCEDURE, SELECT or UPDATE and I have tried Delete FROM table_name However that throws an DBConcurrenceyException.
Here is what I have to tried to clear the table:
private void ClearBut_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableClear = new OleDbDataAdapter();
OleDbCommand command;
command = new OleDbCommand("DELETE FROM TestTable", con);
dtaAdpTestTableClear.DeleteCommand = command;
foreach (DataRow row in dsWCSDHDB.Tables["TestTable"].Rows)
{
row.Delete();
}
dtaAdpTestTableClear.Update(dsWCSDHDB.Tables["TestTable"]);
}
My other add method
private void Add_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableInsertNewRow = new OleDbDataAdapter();
OleDbCommand command;
// Create the InsertCommand.
// This is needed as DataAdaptor.InsertCommand() is called during the update to insert the row into the database. It requires an insert query
command = new OleDbCommand("INSERT INTO TestTable (id, someData) " +"VALUES (?, ?)", con); //We create a dbcommand the command is, Querytype, what we are doing with it, what table, (columns we are using), concat, Values we will be adding(as ? for now as we will pass this data in latter), connection to the database
command.Parameters.Add("id", OleDbType.Char, 5, "id"); //this is where we add a parameter to the command function. we add one per column in the row (columns we are using name, value type, column length, source column, these parameters will replace the ? in the query above
command.Parameters.Add("someData", OleDbType.VarChar, 40, "someData");
dtaAdpTestTableInsertNewRow.InsertCommand = command;// we attach this command to the Insert command function of the adapter that we are using
//Create the new row
DataRow row = dsWCSDHDB.Tables["TestTable"].NewRow(); //Create a new empty row that is formated for the TestTable table
row["someData"] = AddValueTextBox.Text.ToString();// add in the values
//Add the new row to the dataset table
dsWCSDHDB.Tables["TestTable"].Rows.Add(row); //adds this new row to the clients dataset
//Updates the database table with the values of the clients dataset Table
//For this to work you need to build a proper data adapter that is using a query taylered for the table you are using.
//Unfortunately although it would be nice to be able to add and use tables to the database with out changing the code you cant build a generic one that works for all tables in the database.
//this is because different tables can have different fields and column lengths .
//there is a example of how to build one below
//Update the database table with the values of the clients dataset Table
dtaAdpTestTableInsertNewRow.Update(dsWCSDHDB.Tables["TestTable"]); // using the adapter that we created above we update the database with the clients dataset.
}
You will just need to call ExecuteNonQuery
private void ClearBut_Click(object sender, EventArgs e)
{
string comand = "DELETE FROM TestTable";
OleDbCommand cmd = new OleDbCommand(comand, con);
cmd.ExecuteNonQuery();
}
I implemented a search of my nested gridview, and All is working well. But when the gridview loads, it is displaying duplicate rows in the parent table.
As you can see in the picture, There are 2 books under the CourseID of AC107. But my Gridview is displaying a row for each textbook in the course. I have messed with this select statement and anyway I alter it to see if anything works, the gridview doesnt load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//i'm using a datatable for storing all the data
DataTable dt = new DataTable();
string query = "select * from Course inner join textBooks on textBooks.CourseID = Course.CourseID";
//wrapping in 'using' means the connection is closed an disposed when done
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ToString()))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
try
{
//fill the datatable with the contents from the database
adapter.Fill(dt);
}
catch
{
}
}
//save the datatable into a viewstate for later use
ViewState["allBooks"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Below is a layout of my data tables.
Are you sure your SQL query not fetching you the duplicate rows, use ROW_NUMBER() function and see how it works like (assuming you are using SQL Server since you are using SqlConnection provider class)
SELECT * FROM (
select Course.*,
ROW_NUMBER() OVER(PARTITION BY Course.CourseID ORDER BY Course.CourseID) AS rn
from Course
inner join textBooks
on textBooks.CourseID = Course.CourseID ) xxx
WHERE rn = 1;
Here I am trying to load the dropdownlist box from a column of a table in Mysql(which contains repeated values), so I need to get unrepeated values.
This is my code:
MySqlConnection cn = new MySqlConnection("Connection String");
MysqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
cn.Open();
cmd = cn.createcommand();
cmd.CommandText = "Select Columnname from tablename";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DropDownList.Items.Add(reader.GetString("Columnname"));
}
}
cn.close();
}
Try editing your SQL query to get DISTINCT results
cmd.CommandText = "SELECT DISTINCT Columnname FROM tablename";
The code snippet is then presumably called more than once, maybe on each post back. Just clear the items first:
DropDownList.Items.Clear();
One thing to note is that when ViewState is enabled there is no need to reload your drop down lists on each subsequent post back. That also means that you can decide rather to execute this code only if if (!this.IsPostBack)`.
table1:
id name
1 saravanan
2 karumbasalam G
3 saravanan
select distinct name from table1
output:
name
saravanan
karumbasalam G
Use the distinct keyword used to avoid duplicates