How to make insert operation using MySqlDataAdapter in ASP.NET - c#

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.

To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}

Related

Retrieve data from a another table and insert into a another

I'm trying to retrieve data from a table according to the ID number and insert it to another table. The program is in C# and database in MySQL.
The retrieving table name is student_dt and the table name i want to insert is student_att
Here's what I'm doing so far
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "Insert into student_att values(`id`, `nic`, `name`, `address`, `number`, `batch`)";
string Query1 = "select * from student_dt where id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
You can do from one query
string query = "insert into student_att (`id`, `nic`, `name`, `address`,
`number`, `batch`) select * from student_dt where id like '" + textBox1.Text + "%'"

Sql to select the prerequisite of a certain course

I have a table that has courses details as follows:
And, in the Windows, form I placed a textBox and a button, when a student writes the name of the course to see the prerequisite requirement of that course as follows:
So I tried using the following code:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select Name from Courses where (Name = '" + textBox2.Text + "') and Preq = Code";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView3.DataSource = dt;
conn.Close();
textBox2.Text = "";
However, the code gives me the name column without any data as follows:
Also, is there a way to show a message when the course does not have any requirement such as " this course has no prerequisite requirement " something like that?
your query is wrong , the below query returns the list of courses that are requirement for the given course name :
select Name from Courses
where code IN ( select PREQ from Courses where
Name = '" + textBox2.Text + "')
also It would be easier to handle showing a message in your c# code to show if there is no preq.you can checking if dt is null or not .

Add referenced name instead of ID from comobox

I have 2 tables. First has column (categoryID) that is foreign key for categoryID in second table.Second table has 2 columns (categoryID, categoryName). After bit struggling I've displayed in combobox categoryName instead of categoryID. But now when I want to choose from existing categoryName that is already created (displayed in dropdown in combobox), is not possible because I have to type there int not string format. I'm beginner in programming
con.Open();
string cmddt = "insert into wallettbl(sum, date, categoryID, type)
values ('" + textBox1.Text + "','" + textBox2.Text + "','" +
comboBox1.Text + "', '" + type + "')";
SqlCommand com = new SqlCommand(cmddt, con);
com.ExecuteNonQuery();
How to write code if I want to add string (from combobox) instead of int, but in first table will be added categoryID which is referenced to categoryName.
EDIT: added code for combobox
con.Open();
string cmddt = "select categoryNAME from categoryTbl";
SqlCommand com = new SqlCommand(cmddt, con);
SqlDataAdapter da = new SqlDataAdapter(cmddt, con);
DataSet ds = new DataSet();
da.Fill(ds);
com.ExecuteNonQuery();
con.Close();
change the query to load the categories as below:
string cmddt = "select categoryID, categoryNAME from categoryTbl";
Set the datasource for comboBox1 as below:
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "categoryNAME";
comboBox1.ValueMember = "categoryID";
and finally modify the code to insert data into the wallettbl as follows:
string cmddt=
#"INSERT INTO WALLETTBL(sum, date, categoryID, type)
VALUES (#Sum, #Date, #CategoryId, #Type);";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add("#Sum", SqlDbType.Int).Value = textBox1.Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = textBox2.Text;
cmd.Parameters.Add("#CategoryId", SqlDbType.Int).Value = Convert.ToInt32(comboBox1.SelectedValue);
cmd.Parameters.Add("#Type", SqlDbType.Varchar).Value = type;
await conn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}

select , update Query c# error

I am importing excel file into sql database.Working code I am Using is:
public static void ImportToSql(string excelfilepath)
{
string ssqltable = "Inventory";
string myexceldataquery = "select LocalSKU,QOH from [sheet1$]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + excelfilepath + "; Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=2\"";
string ssqlconnectionstring = "Data Source=DELL\\SQLSERVER1;Trusted_Connection=True;DATABASE=CAMO;CONNECTION RESET=FALSE";
//execute a query to erase any previous data from our destination table
string sclearsql = "delete " + ssqltable;
enter code here
"HERE I DON'T WANT THIS STEP TO DELETE TABLE DATA AND THEN INSERTING IT.INSTEAD I WANT TO UPDATE TABLE DATA"
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
while (dr.Read())
{
//bulkcopy.WriteToServer(dr);
}
Console.WriteLine(".xlsx file imported succssessfully into database.", bulkcopy.NotifyAfter);
oledbconn.Close();
}
I don't know how to update it that's why what I do is I delete data and then insert. Please help me with Updating columns QOH based on primarykey table LocalSKU.
I tried the following thing but it gives error saying "Merge statement must be terminated by a semi-column(;)"
SqlCommand sqlcmd = new SqlCommand(#"MERGE Inventory AS target
USING (select LocalSKU, QOH from #source) as source
ON (source.ID = target.ID)
WHEN MATCHED THEN
UPDATE SET QOH = source.QOH
WHEN NOT MATCHED THEN
INSERT (LocalSKU, QOH )
VALUES (source.LocalSKU, source.QOH )", sqlconn);
SqlParameter param=new SqlParameter();
sqlcmd.Parameters.AddWithValue("#source", ssqltable);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.tStudent";
Basically I want only two columns KitSKU and Quantity out of many
columns in table Kits.
Change:
SqlDataAdapter da = new SqlDataAdapter("select * from [KitSKU] , [Quantity] from Kits", sqlCon);
To:
SqlDataAdapter da = new SqlDataAdapter("select [KitSKU] ,[Quantity] from Kits", sqlCon);
you want to select column: [KitSKU] and [Quantity] from table: Kits
Thanks Max.. also If I want to Update it rather than inserting, how to
implement that.
Use following code, for updating KitSKU and Quantity:
SqlDataAdapter da = new SqlDataAdapter("update Kits set [KitSKU] = 'entersku' ,[Quantity] = 5 where [KutSKU] = 'what record it should update'", sqlCon);
But I wouldn't recommend that code, since it isn't parameterized and I think you should try with some basic sql lessons and using sql parameters.

Working on three tier in c# but my insert query is not working

access layer:
public bool AddStudent(string busStudentFullName, string busStudentFatherName)
{
con = new SqlCeConnection();
con.ConnectionString = "data source = C:\\Users\\hasni\\Documents\\Visual Studio 2010\\Projects\\UniversityManagementSystem\\UniversityManagementSystem\\UniversityDB.sdf";
con.Open();
ds1 = new DataSet();
//DataTable t = new DataTable();
// string sql = "SELECT * from AdminPassword where Admin Name ='" + AdminNameLogintextBox.Text + "' and Password='" + PasswordLogintextBox.Text + "'";
//string qry = "SELECT * FROM Students";
// string sql = "SELECT * from AdminPassword where Admin Name ='" + AdminNameLogintextBox.Text + "' and Password='" + PasswordLogintextBox.Text + "'";
string sql = "SELECT * FROM Students";
da = new SqlCeDataAdapter(sql, con);
//da = new SqlCeDataAdapter();
//DataTable t = new DataTable();
//da.Fill(t);
da.Fill(ds1, "Students");
//string userNameDB = Convert.ToString(ds1.Tables[0]);
// return userNameDB;
con.Close();
// string busStudentFullName;
//string busStudentFatherName;
string sql2 = "INSERT INTO Students (Student Full Name,Student Father Name) Values('"+ busStudentFullName + "','" + busStudentFatherName + "')";
da = new SqlCeDataAdapter(sql2, con);
da.Fill(ds1, "Students");
con.Close();
return true;
}
Business layer:
public bool getResponseForAddStudent(string studentName, string studentfathername)
{
bool var = access.AddStudent(studentName, studentfathername);
return var;
}
Presentation layer:
private void AddStudentButton_Click(object sender, EventArgs e)
{
string studentName = StudentNameBox.Text;
string studentfathername = StdFatherNameBox.Text;
bool var = _busGeneral.getResponseForLogin(studentName, studentfathername);
if (var)
{
MessageBox.Show("Student Added");
}
else
{
MessageBox.Show("Sorry");
}
}
Your Sql isn't valid, when columns have spaces in their name need to surround with square brackets: INSERT INTO Students (Student Full Name,Student Father Name)
instead needs to be
INSERT INTO Students ([Student Full Name],[Student Father Name])
If I understand what you are attempting to do, there are a number of issues with your code in addition to the brackets problem.
Firstly, you are closing the connection before performing the last DataAdapter.Fill operation.
And since you want to insert a record before (re)filling the DataAdapter with student data, you must first issue a ExecuteNonQuery statement using a SqlCeCommand object. Also, to avoid injection attacks and other problems you should ALWAYS use parameterized queries. I would also advise wrapping the code with try...catch to handle errors.
Here is what I think you are trying to achieve with the insert operation (I have only desk-checked the syntax):
// con.Close();
// string busStudentFullName;
SqlCeCommand cmd = db.CreateCommand();
cmd.CommandText = "INSERT INTO Students ([Student Full Name],[Student Father Name]) Values(#FullName, #DadsName)";
cmd.AddParameter("#FullName", busStudentFullName);
cmd.AddParameter("#DadsName", busStudentFatherName);
cmd.ExecuteNonQuery();
At this point you can fill the DataAdapter with student rows including the newly inserted one.

Categories

Resources