MySQL trigger + insert - c#

i'm trying to get my current id from a table pk to insert on another table fk, my next try is set a trigger inside database.
CREATE PROCEDURE `INSERIR CODIGO DISPENSACAO` ()
CREATE TRIGGER `productInsert`
BEFORE INSERT ON `produtos_disp`
FOR EACH ROW
BEGIN
set NEW.ID_PRODISP = (select max(ID)
from dispensacao p
);
END
what I want to set max id from dispensacao table which is going to be inserted from auto_increment on insert to it, on my fk codigo_disp for every row.

Managed to get max id using a combobox as descending order.
used
MySqlConnection connection = new MySqlConnection("connectionString");
string selectQuery = "select ID from dispensacao ORDER BY id DESC LIMIT 1";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbid.DisplayMember = "ID";
Cmbid.DataSource = dt2;
this return the max id from the table and all you need to do is make it invisible so user won't change as it is a combobox

Related

Show data of table when clicking on a value - SelectionChanged

Whenever I click on a name in EmployeeRank1 List listbox I want to get in the EmployeeRank1Information listbox associated data from the table for it. However, I get an exception instead. Screenshots and code used provided below.
Table
WPF Window
Exception
Code I have used
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue != null)
{
// use a try-catch, in case we run into an
// error while digging into the database
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#name", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1InformationTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1InformationTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1Information.DisplayMemberPath = "Salary";
employeeRank1Information.DisplayMemberPath = "Position";
employeeRank1Information.DisplayMemberPath = "Responsibility";
employeeRank1Information.DisplayMemberPath = "Age";
employeeRank1Information.DisplayMemberPath = "YearsInCompany";
employeeRank1Information.SelectedValuePath = "Id";
employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
}
}
catch (Exception exception)
{
// show what is the error
MessageBox.Show(exception.ToString());
}
}
}
You could just pass Id into the query, as that is the primary key of Employee
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue == null) // less nesting to flip the condition
return;
try
{
// only select the columns you need
const string query = #"
select
Id,
Name,
Salary,
Position,
Responsibility,
Age,
YearsInCompany
from EmployeeRank1 e
where e.Id = #id
";
// always use a new connection and dispose it
using (SqlConnection sqlConnection = new SqlConnection(yourConnectionString))
// Create an SqlCommand and connect to the database
using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
{
// always specify parameter type (and length for strings)
sqlCommand.Parameters.Add("#id", SqlDbType.Int).Value = ((DataRow)employeeRank1List.SelectedValue)["Id"];
// how do you get the Id column??
DataTable employeeRank1InformationTable = new DataTable();
conn.Open();
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
employeeRank1InformationTable.Load(reader);
}
} // close connection as quick as you can
// you can only set one column to display
employeeRank1Information.DisplayMemberPath = "Name";
employeeRank1Information.SelectedValuePath = "Id";
employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
}
catch (Exception exception)
{
// show what is the error
MessageBox.Show(exception.Message);
}
}
You have declared where conditions for these without value
AND Salary = #salary AND
Responsibility = #responsibility AND
Position = #position AND
Age = #age AND
YearsInCompany = #yearsInCompany
You need to Fille them before executing the query
sqlCommand.Parameters.AddWithValue("#Salary", <VALUE FROM TABLE>);
Since you have not specified how you fill the gridview or table,
you need to get the following values yourself
Your SQL query contains 6 Conditions.
select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany.
but you have only filled one using -
sqlCommand.Parameters.AddWithValue("#name", employeeRank1List.SelectedValue);
so basically the query is equal to this when clicking on a list item
select * from EmployeeRank1 where Name = <LitsView Item>
AND Salary = UNDEFINED
AND Responsibility = UNDEFINED
AND Position = UNDEFINED
AND Age = UNDEFINED
AND YearsInCompany = UNDEFINED;
now UNDEFINED here makes it a SQL syntax error since the scalar variables are missing. to get it to work, here is a workaround for you to understand how it works-
change this line in your code
string query = "select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany";
to this
string query = "select * from EmployeeRank1 where Id = #name";
after you try this it should work with inaccurate results. to make it work properly fill the rest of the where conditions in your SQL code
Also, use a primary/unique key to locate records instead of using #NAME
I managed to make it work by having multiple listboxes instead of one. Moreover, in the query I selected the id only, which is the primary key and then added multiple try-catch blocks in order to fill those listboxes that I had created. A screenshot of the working program, as well as the code
Program
Code
// a method that shows information for employees that are rank 1
private void ShowEmployeeRank1Information()
{
// use a try-catch, in case we run into an
// error while digging into the database
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1PositionTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1PositionTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1PositionList.DisplayMemberPath = "Position";
employeeRank1PositionList.SelectedValuePath = "Id";
employeeRank1PositionList.ItemsSource = employeeRank1PositionTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1AgeTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1AgeTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1AgeList.DisplayMemberPath = "Age";
employeeRank1AgeList.SelectedValuePath = "Id";
employeeRank1AgeList.ItemsSource = employeeRank1AgeTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1ResponsibilityTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1ResponsibilityTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1ResponsibilityList.DisplayMemberPath = "Responsibility";
employeeRank1ResponsibilityList.SelectedValuePath = "Id";
employeeRank1ResponsibilityList.ItemsSource = employeeRank1ResponsibilityTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1YearsInCompanyTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1YearsInCompanyTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1YearsInCompanyList.DisplayMemberPath = "YearsInCompany";
employeeRank1YearsInCompanyList.SelectedValuePath = "Id";
employeeRank1YearsInCompanyList.ItemsSource = employeeRank1YearsInCompanyTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
}
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue != null)
{
ShowEmployeeRank1Information();
}
}

C# SQL query - try to use sum(weekly_slot) FROM group by

I am trying to sum weekly_slot according to Teacher_Name from GroupOdd dbtable, however I am getting 10 values for all row. Appreciate if can correct me. Beside that, how to update GroupOdd dbtable to sort according to larger sum_weekly_slot first?
Thanks.
cmd2 = new SQLiteCommand();
cmd2 = dbConnect.CreateCommand();
//cmd2.CommandText = "DELETE FROM GroupOdd";
//cmd2.ExecuteNonQuery();
cmd2.CommandText = "SELECT Sum(Weekly_Slot) AS Sum_Weekly_Slot FROM GroupOdd group by Teacher_Name";
DataTable dt2 = new DataTable();
SQLiteDataAdapter da2 = new SQLiteDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
//cmd.CommandText = "INSERT INTO GroupOdd (Teacher_Name, Standard, Subject, Weekly_Slot, Balance_Slot) VALUES (#Teacher_Name, #Standard, #Subject, #Weekly_Slot, #Balance_Slot)";
cmd2.CommandText = "UPDATE GroupOdd SET Sum_Weekly_Slot = #Sum_Weekly_Slot";
//cmd2.Parameters.AddWithValue("#Sum_Weekly_Slot", dr2["Sum(Weekly_Slot)"].ToString());
cmd2.Parameters.AddWithValue("#Sum_Weekly_Slot", dr2["Sum_Weekly_Slot"].ToString());
cmd2.ExecuteNonQuery();
}
All you need is a GROUP BY clause with the MAX aggregate function:
SELECT id, MAX(rev)
FROM YourTable
GROUP BY id
Than Update it accordingly.
IF
Sum(Weekly_Slot);
is not what u looking for
try
Count(Weekly_Slot)
SELECT Teacher_Name, Sum(Weekly_Slot) AS Sum_Weekly_Slot FROM GroupOdd
group by Teacher_Name order by Sum(Weekly_Slot) desc
Check the Teacher_Names are unique, else try to use an Id (TeacherId) for Teachers. The order by Sum(Weekly_Slot) desc should sort the table by largest first.

Fetch column schema from tables of mysql datatable

I want to fetch column schema with full details from Mysql Database.
I am having two tables where Customer table schema is like as
And another table Orders table schema is like this
I want to fetch these column schema with respect to my join query which is
using (MySqlConnection myConnection = new MySqlConnection("Server=xxxx;Uid=is;Pwd=password;Database=mydatabse"))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT a.CustomerID, a.PostalCode, b.Freight, b.ShippedDate
FROM orders b, customers a
WHERE a.CustomerID = b.CustomerID Limit 5;", myConnection))
{
myConnection.Open();
using (MySqlDataReader mdr = cmd.ExecuteReader())
{
DataSet ds = new DataSet();
ds.Tables.Add("Customers");
mdr.Read();
DataRow dr;
dt.Columns.Add("ColName");
dt.Columns.Add("ColType");
for (int k = 0; k <= mdr.FieldCount - 1; k++)
{
dr = dt.NewRow();
dr["ColName"] = mdr.GetName(k);
dr["ColType"] = mdr.GetDataTypeName(k);
dt.Rows.Add(dr);
}
}
}
}
I need the full detail schema of the selected columns which I have used in join query.
I have used GetDataTypeName() to retrieve column type but it only returns datatype.
I found this query
select * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'nsightsmysqldata' AND TABLE_NAME = 'customers';
which returns all detail relating to that table but I need only those column details which I had used in join query above.
Please provide me possible solution.
It turns out that you can do that with the
connection object
Well at least it worked for me in powershell.
$conn.GetSchema("Columns") will return every column schema in the current database as a DataTable

Adding a unique identifier to a c# form to be inserted into an mssql database

I am trying to link my c# form to a database that can hold all the data that is inserted in the form.
the other four fields are being inserted into the database correctly.
the problem that I am having is that every time a new record is created, a unique identifier needs to be generated in the last field of the SQL table.
The only way I can do this is by using a guid. But the problem is that I need the Identifier to start from 1 and increment.
I'm not sure how to do this in C# so any help provided would be excellent.
Here is my code
protected void Unnamed1_Click(object sender, EventArgs e)
{
string box1value = TextBox1.Text;
string box2value = TextBox2.Text;
string box3value = TextBox3.Text;
SqlConnection myConnection = new SqlConnection(sConnection);
string sql = "INSERT INTO Part1Table (CustomerDetails, TechnologyPartner, ResponseDate, FormID, RowID) VALUES (#CustomerDetails, #TechnologyPartner, #ResponseDate, #FormID, #RowID)";
myConnection.Open();
try
{
// create a db command objet using the sql and db connection
SqlCommand cmdIns = new SqlCommand(sql, myConnection);
//box1value
cmdIns.Parameters.Add("#CustomerDetails", SqlDbType.Char);
cmdIns.Parameters["#CustomerDetails"].Value = box1value;
//box2value
cmdIns.Parameters.Add("#TechnologyPartner", SqlDbType.Char);
cmdIns.Parameters["#TechnologyPartner"].Value = box2value;
//box3value
cmdIns.Parameters.Add("#ResponseDate", SqlDbType.DateTime);
cmdIns.Parameters["#ResponseDate"].Value = box3value;
cmdIns.Parameters.Add("#FormID", SqlDbType.Int);
cmdIns.Parameters["#FormID"].Value = 1;
cmdIns.Parameters.Add("#RowID", SqlDbType.UniqueIdentifier);
cmdIns.Parameters["#RowID"].Value = Guid.NewGuid();
// run the query
cmdIns.ExecuteNonQuery();
// end the command object
cmdIns.Dispose();
cmdIns = null;
}
catch(Exception ex)
{
Response.Write(ex);
}
myConnection.Close();
You are looking for an IDENTITY COLUMN
For Example
CREATE TABLE [dbo].[Part1Table](
[CustomerDetail] [nvarchar](50) NULL,
....
[RowID] [int] IDENTITY(1,1) NOT NULL
CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
(
[RowID] ASC
)ON [PRIMARY]
If you have an identity column, the job to add an increment value to every new record, is passed to the database engine.
Of course you cannot pass a value yourself for this column, but you read the value assigned by the database using the command SCOPE_IDENTITY
SELECT SCOPE_IDENTITY()
So, summarizing you could write
string sql = #"INSERT INTO Part1Table (CustomerDetails, TechnologyPartner, ResponseDate,
FormID) VALUES (#CustomerDetails, #TechnologyPartner, #ResponseDate, #FormID)";
using(SqlConnection myConnection = new SqlConnection(sConnection))
SqlCommand cmdIns = new SqlCommand(sql, myConnection);
{
try
{
myConnection.Open();
cmdIns.Parameters.Add("#CustomerDetails", SqlDbType.Char);
cmdIns.Parameters["#CustomerDetails"].Value = box1value;
//box2value
cmdIns.Parameters.Add("#TechnologyPartner", SqlDbType.Char);
cmdIns.Parameters["#TechnologyPartner"].Value = box2value;
//box3value
cmdIns.Parameters.Add("#ResponseDate", SqlDbType.DateTime);
cmdIns.Parameters["#ResponseDate"].Value = box3value;
cmdIns.Parameters.Add("#FormID", SqlDbType.Int);
cmdIns.Parameters["#FormID"].Value = 1;
// No parameter for the ROWID column.
// It will be an error to try to insert
// a value for that column
cmdIns.ExecuteNonQuery();
// Read back the value using the SAME connection used for the insert
cmdIns.Parameters.Clear();
cmdIns.CommandText = "SELECT SCOPE_IDENTITY()";
object result = cmdIns.ExecuteScalar();
int newRowID = Convert.ToInt32(result);
}
}

using ON DUPLICATE KEY UPDATE insert query for update already exist row

connection()
{
OleDbConnection nwindConn=new OleDbConnection();
MySql.Data.MySqlClient.MySqlConnection con= new MySqlConnection();
MySqlCommand cmd;
con.ConnectionString ="server=localhost;" +
"uid=root;"+
"pwd=;" +
"database=globasys;" ;
DateTime dt=DateTime.Now;
string select = "SELECT CategoryID, CategoryName FROM categories";
MySqlDataAdapter catDA = new MySqlDataAdapter(select, con);
string insert = "insert into categories(CategoryID,CategoryName)
VALUES(#CategoryID,#CategoryName)
ON DUPLICATE KEY UPDATE CategoryID=#CategoryID";
catDA.InsertCommand = new MySqlCommand(insert, con);
catDA.InsertCommand.Parameters.Add("#CategoryID", MySqlDbType.Int32
, 11, "CategoryID");
catDA.InsertCommand.Parameters.Add("#CategoryName", MySqlDbType.VarChar
, 250, "CategoryName");
DataSet catDS = new DataSet();
catDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
catDA.Fill(catDS, "Categories");
DataSet newdt = new DataSet();
newdt = getnewdata();
int i= catDA.Update(newdt, "Categories");
}
public DataSet getnewdata()
{
DataSet catDS=new DataSet();
DataTable dt = new DataTable();
DataColumn col1 = new DataColumn("CategoryID", typeof(int));
dt.Columns.Add(col1);
DataColumn col=new DataColumn("CategoryName",typeof(string));
dt.Columns.Add(col);
DataColumn[] Cols = { dt.Columns[0] };
dt.PrimaryKey =Cols;
DataRow crow = dt.NewRow();
crow["CategoryID"]=1;
crow["CategoryName"]="io";
dt.Rows.Add(crow);
dt.TableName = "Categories";
DataRow crow1 = dt.NewRow();
crow1["CategoryID"] = 3;
crow1["CategoryName"] = "p";
dt.Rows.Add(crow1);
dt.TableName = "Categories";
catDS.Tables.Add(dt);
return catDS;
}
I want the insert command ON DUPLICATE KEY UPDATE to update the old values with the new values. If the values does not exist then it needs to insert a new value.
It does execute, but it does not update the existing value
considering my table
1 a
2 b
Using this query
INSERT INTO categories(CategoryID,CategoryName)
VALUES(1,qq) ON DUPLICATE KEY UPDATE CategoryID = 1
then I want the outcome to be
1 qq
2 b
You're using the wrong command.
Use this query instead:
REPLACE INTO categories (CategoryID,CategoryName)
VALUES(1,qq);
Here's why your query does not work
INSERT INTO categories(CategoryID,CategoryName)
VALUES(1,qq) ON DUPLICATE KEY UPDATE CategoryID = 1
This code tries to insert 1 into CategoryID that doesn't work, because 1 is already in the table.
Next the ON DUPLICATE KEY clause runs.
This sets CategoryID to 1.
But is was 1 before, it's 1 after so nothing has changed and you are still trying to insert a duplicate key.
After that MySQL is out of options and gives up.
You are using the right statement but in the wrong way.
Instead of
INSERT INTO categories(CategoryID,CategoryName)
VALUES(1,"qq") ON DUPLICATE KEY UPDATE CategoryID = 1
you should write
INSERT INTO categories(CategoryID,CategoryName)
VALUES(1,"qq") ON DUPLICATE KEY UPDATE CategoryName = VALUES(CategoryName)
because after the keyword UPDATE you have to put the columns that you want to change, which in your case is CategoryName. VALUES(CategoryName) means that the new value is the one that you already stated for the INSERT - which is "qq", in the example.
This is the official documentation: http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
This statement is better than REPLACE INTO for several reasons. See here, for instance: Insert into a MySQL table or update if exists

Categories

Resources