I'm new at coding and I need help for a school project.
I want to update a database using MySQL but I can't find out how to get the update working.
I have googled a bit but I haven't been able to find a solution so I figured I'd ask the question on this site.
I have successfully made a connection to the database and show the contents in a data grid. The connection has a name: "conn". If anyone knows a way on how I can get the update to work I'd be happy to hear from you!
This is my XAML.CS code:
public void Click_btnBewerk(object sender, RoutedEventArgs e)
{
string vzitter2 = txtVZitter.Text;
string info2 = txtInfo.Text;
string zetels2 = txtZetels.Text;
string stroming2 = txtStroming.Text;
string partij = cmPartijen.Text;
conn.Updateinfo();
}
This is my DBconn code:
public DataView Updateinfo()
{
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "UPDATE partijen SET fvzitter='vzitter2', info='info2', zetels='zetels2', stroming='stroming2' WHERE partij='partij'";
MySqlDataReader reader = command.ExecuteReader();
DataTable dtData = new DataTable();
dtData.Load(reader);
conn.Close();
return dtData.DefaultView;
}
you are doing a Reading action on the db instead an update.
Just replace your code with this
public void Updateinfo()
{
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "UPDATE partijen SET fvzitter='vzitter2', info='info2', zetels='zetels2', stroming='stroming2' WHERE partij='partij'";
command.ExecuteNonQuery();
conn.Close();
}
if you want pass the variables to the updateinfo method just do it
private void Updateinfo(string fvzitter, string info, string zetels, string stroming, string partij)
{
string query = "UPDATE partijen SET fvzitter=#fvzitter, info=#info, zetels=#zetels, stroming=#stroming WHERE partij=#partij"
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = query;
command.Parameters.AddWithValue("#fvzitter", fvzitter);
command.Parameters.AddWithValue("#info", info);
command.Parameters.AddWithValue("#zetels", zetels);
command.Parameters.AddWithValue("#stroming", stroming);
command.Parameters.AddWithValue("#partij", partij);
command.ExecuteNonQuery();
conn.Close();
}
Related
I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}
How do I link textboxes?
Scenario:
TextBox_Supplier
TextBox_Address
TextBox_Supplier is autocomplete and it's working. When typing is done in TextBox_Supplier, the TextBox_Address will select supplier's address.
My code does not work:
private void txb_vendor_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txb_address.Text))
{
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon.getcon();
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name = {0}",txb_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
address = txb_address.Text;
}
PurCon.con.Close();
}
}
Thank you for helping me!
instead of
address = txb_address.Text;
write
txb_address.Text = address;
Try to use Parameterized Query instead of concatenation of the strings.
Do Change as #Mohit suggested and also wrap the supplier name with single quotes, since supplier name is string type and in sql String should be wrap in single Quotes other wise this will give SQL Error
"SELECT address FROM tbl_Supplier WHERE supplier_name = '{0}'"
----^
I already solved this problem last week. And I'm so angry to myself!
The textbox_Address does not changed once, it stacks up when the textbox_Supplier_TextChaged. So I put Clear() method to clear previous input address.
public void AddressTbxLoad()
{
DBCon PurCon = new DBCon();
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon2.con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name LIKE '{0}%'", cbx_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
txb_address.Text = address;
}
PurCon.con.Close();
}
private void cbx_vendor_SelectedIndexChanged(object sender, EventArgs e)
{
txb_address.Clear();
AddressTbxLoad();
}
private void Purchase_Load(object sender, EventArgs e)
{
VendorTbxLoad();
}
Hi im trying to insert data into my DataBase. The program runs but it never save the values!!.
heres the code:
using System.Data.SqlClient;
namespace Database_1._0
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"DataSource=LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Luis\documents\visual studio 2015\Projects\Database_1._0\Database_1._0\DB.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DateTime dateTime = DateTime.UtcNow.Date;
string user = "1614258779876465426";
string pass = "3Cp5CeXrfghdfght";
string frecuencyCode = "ANNUAL";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void logo_Click(object sender, EventArgs e)
{
MessageBox.Show("Database_1._0 \nWritten by: Luis", "About");
}
private void button1_Click(object sender, EventArgs e)
{
cn.Open();
using (SieteWS SieteWS = new SieteWS())
{
Respuesta respuesta = SieteWS.SearchSeries(user, pass, frecuencyCode);
foreach (internetSeriesInfo seriesInfo in respuesta.SeriesInfos)
{
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
}
and the Error says:
errorCS0103: The name 'CommandText' does not exist in the current context. And when I use a watch I found out this: cmd.CommandText =""; . Can somebody tell me what im doing wrong please.?
So first of all. move cn.Close(); outside of the loops. If it's not the cause for your problem now, it will cause a problem later.
If that doesn't fix your problem look further.
It's just a poke in the dark given the information I have, but try running following code sets (inside foreach loop) and see if any of them work:
set 1:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES ('"+seriesInfo.seriesId+"', '"+seriesInfo.spanishTitle+"'
, '"+seriesInfo.frequency+"')", cn);
cmd.ExecuteNonQuery();
set 2:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES (#SerieID, #SerieName, #SerieFrecuency)", cn);
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
Let me know how it works out
Try this...
Modify the line below to include the name of the database. So that it will read [Your database Name].[dbo].[Serie]
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
Your default database may not be the one that has your "Serie" table in it.
I have set up a listbox called lboxsupplier, i have also created a data adapter which i then used to populate the supplier listbox. When i run the form the listbox is empty. I want the listbox to populate with supplier ID and company which i will then click on to populate another listbox with products.
Namespace Pennyburn_Greg
{
public partial class FormProcess : Form
{
SqlDataAdapter daSupplier;
DataSet dsPennyburnGreg = new DataSet();
SqlConnection conn;
SqlCommand cmdSupplierDetails;
SqlCommandBuilder cmdBSupplier;
DataRow drSupplier;
String connstr, sqlSupplier;
public FormProcess()
{
InitializeComponent();
}
private void FormProcess_Load(object sender, EventArgs e)
{
connstr = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
//dataAdapter for supplier listbox
sqlSupplier = #"Select* from Supplier";
conn = new SqlConnection(connstr);
cmdSupplierDetails = new SqlCommand(sqlSupplier, conn);
daSupplier = new SqlDataAdapter(cmdSupplierDetails);
daSupplier.FillSchema(dsPennyburnGreg, SchemaType.Source, "Supplier");
}
private void filllboxsupplier(string str)
{
daSupplier.Fill(dsPennyburnGreg, "Supplier");
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"];
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
}
}
}
First of all, why are you calling FillSchema, rather should be calling Fill method to get the data, like
daSupplier.Fill(dsPennyburnGreg, "Supplier");
Once you have the dataset filled, then in your FormProcess_Load() you can add the dataset as datasource to the listbox like
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"]
First thing you need to do is loosely couple your UI and data a little bit. Try this code:
// Returns a DataTable of ALL suppliers
private DataTable GetSuppliers()
{
return GetSuppliers(0);
}
// Returns a DataTable of the given supplier
private DataTable GetSuppliers(int supplierId)
{
using (var connection = new SqlCommand())
{
connection.ConnectionString = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
using (var command = new SqlCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.Connection = connection;
if (supplierId == 0)
{
command.commandText = "SELECT * FROM Supplier";
}
else
{
command.commandText = "SELECT * FROM Supplier WHERE SupplierId=#id";
command.Parameters.AddWithValue("#id", supplierId);
}
using (var adapter = new SqlDataAdapter())
{
using (var ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
return ds.Tables[0];
}
}
}
}
return null;
}
And now you can just do this:
lboxsupplier.DataSource = GetSuppliers(int.Parse(lboxsupplier.SelectedValue));
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
Or if you need all Suppliers, just do this:
lboxsupplier.DataSource = GetSuppliers();
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
This code will provide some separation. This is still not ideal, but beats what you had.
You're not doing anything with the listbox control in FormProcess_Load, so it will be empty when it first loads. I'm assuming you have lboxsupplier_Click bound to the Click event of lboxsupplier? If so, then you'll need to click on that listbox before it will populate the Dataset (which is a very odd user experience, but if that's truly what you need...). If lboxsupplier_Click isn't an event handler, then you're going to have to manually call it.
If it still isn't populating, then try running your query against the database directly, and make sure that it returns data and has columns named "Company" and "SupplierID"
Im trying to build up a little status-tool. I need to get results of multiple queries (about 4-5). The general connection-setup and 'how-to-read-data' is already done but I cant figure out how the another query executed.
Everything I found while searching for it is for the SqlClient. Im totally overcharged with this.
Here is my code so far (be patient, im a newbie to this):
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC";
try
{
conn.Open();
}
catch (Exception ex)
{
listView1.Items.Add("Error: " + ex);
}
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
listMember.Add(reader["fullname"].ToString());
listOnline.Add(reader["online"].ToString());
}
conn.Close();
// SQL ENDING //
// SET ENTRIES TO LISTVIEW //
int counter = 0;
foreach(string member in listMember)
{
ListViewItem item = new ListViewItem(new[] { member, listOnline.ElementAt(counter) });
item.ForeColor = Color.Green;
listView1.Items.Add(item);
counter++;
}
}
Im not really sure how the design/layout will look like in the end, so I would like to just append the results to lists in the sql-part to process the data later out of the lists.
Do I really have to setup a complete new connection after conn.Close()? Or is there any other way? I can just imagine: 5 queries with their own connection,try,catch and 2 loops... this will get about 100-200 lines just for getting the results out of 5 queries. Isnt that a bit too much for such an easy thing?
Hope for some help.
Greetings.
According to the new comments my latest code:
Top:
public partial class Form1 : Form
{
public static string connString = "Server=10****;Port=3306;Database=e****;Uid=e****;password=****;";
public Form1()
{
InitializeComponent();
MySqlConnection conn = new MySqlConnection(connString); // Error gone!
}
Body part:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
{
try
{
MySqlCommand cmd = conn.CreateCommand(); // ERROR: conn does not exist in the current context.
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
using (conn) // ERROR: conn does not exist in the current context.
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listMember,listOnline);
//...2nd query
//QueryTwoFields("your new Select Statement", otherList, otherList);
}
}
You don't have to close connection every time you execute one query rarher than close the sqlreader assigned to that connection. Finally when all of your queries have been executed you close the connection. Consider also the use of using:
You cal also define a method for execution your Query in order for your code not to be repetive:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
///Select into List S1 and List S2 from Database (2 fields)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
using (conn)
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listmember,listonline)
//...2nd query
QueryTwoFields("your new Select Statement",myOtherList1,myOtherlist2)
....
}
}
EDIT :
Take in mind you cant define QueryTwoFields method inside button handler. You must define it outside (see code above).
Also Define your connection data in the start of the programm:
namespace MyProject
{
/// <summary>
/// Defiine your connectionstring and connection
/// </summary>
///
public partial class Form1 : Form
{ public static string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
.........
Datatables are fantastic
Using a data table is a nice way to do both read and write. And it comes with the luxury of eveything you can do with a datatable - like asssigning it directly to a datagrid control, sorting, selecting and deleting while disconnected.
The sample below assumes a MySqlConnection conection property managed by calls to your own OpenConnection() and CloseConnection() methods not shown.
Simple datatable read demo:
public DataTable Select(string query = "")
{
//Typical sql: "SELECT * FROM motorparameter"
DataTable dt = new DataTable();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
dt.Load(dataReader);
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return data table
return dt;
}
else
{
return dt;
}
}
In case of writing back the datatable to the database - supply the SQL you used in the read (or would have used to read to the data table):
public void Save(DataTable dt, string DataTableSqlSelect)
{
//Typically "SELECT * FROM motorparameter"
string query = DataTableSqlSelect;
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand mySqlCmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
adapter.Update(dt);
//close Connection
this.CloseConnection();
}
else
{
}
}
The neat thing the datatable is extremely flexible. You can run your own selects against the table once it contains data and before writing back you can set or reset what rows needs updating and by default the datatable keeps track of what rows you update in the table. Do not forget primary key column(s) for all tables in the db.
For multiple queries consider if possible using a join between the database tables or same table if data related or use a UNION sql syntax if column count and type of data is the same. You can allways "create" your extra column in the select to differ what data comes from what part of the UNION.
Also consider using CASE WHEN sql syntax to conditionally select data from different sources.