I'm new in learning C# and MySql using Visual Basic Community 2015, I'm trying to make simple CRUD, but I'm confused when I Run the Program and try to input data to MySql Table because it always shows message
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Siswa,Total Biaya SPP,Sisa Bayar SPP,Keterangan) VALUES
is there any solution for this?
public partial class Crud : Form
{
MySqlConnection conn = new MySqlConnection("Server=localhost;User Id=root;Password='';Database=db_csharp1");
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand();
public DataSet ds = new DataSet();
public Crud()
{
InitializeComponent();
}
private void Crud_Load(object sender, EventArgs e)
{
GetRecords();
}
private void btnTambah_Click(object sender, EventArgs e)
{
ds = new DataSet();
adapter = new MySqlDataAdapter ("INSERT INTO siswa (NIS,Nama Siswa,Total Biaya SPP,Sisa Bayar SPP,Keterangan) VALUES ('"+textNIS.Text+"','"+textNamaSiswa.Text+"','"+textBiayaSPP.Text+"','"+textSisaBayar.Text+"','"+textKeterangan+"')", conn);
adapter.Fill(ds,"siswa");
MessageBox.Show("Added!");
textNIS.Clear();
textNamaSiswa.Clear();
textBiayaSPP.Clear();
textSisaBayar.Clear();
textKeterangan.Clear();
GetRecords();
}
private void GetRecords()
{
ds = new DataSet();
adapter = new MySqlDataAdapter("select * from siswa", conn);
adapter.Fill(ds, "siswa");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "siswa";
}
You have spaces in your column names. Use ` in your column names.
INSERT INTO siswa (`NIS`,`Nama Siswa`,`Total Biaya SPP`,`Sisa Bayar SPP`,`Keterangan`)
In your case, you can use Parametrized query to fill your Dataset. Now since the string used to initialize the SqlDataAdapter becomes the CommandText of the SelectCommand property of the SqlDataAdapter. So you can add your parameters like this:
adapter = new MySqlDataAdapter ("INSERT INTO siswa (`NIS`,`Nama Siswa`,`Total Biaya SPP`,`Sisa Bayar SPP`,`Keterangan`) VALUES (#textNIS,#textNamaSiswa,#textBiayaSPP,#textSisaBayar,#textKeterangan)", conn);
adapter.SelectCommand.Parameters.AddWithValue("#textNIS","%" + textNIS.Text + "%");
adapter.SelectCommand.Parameters.AddWithValue("#textNamaSiswa","%" + textNamaSiswa.Text + "%");
adapter.SelectCommand.Parameters.AddWithValue("#textBiayaSPP","%" + textBiayaSPP.Text + "%");
adapter.SelectCommand.Parameters.AddWithValue("#textSisaBayar","%" + textSisaBayar.Text + "%");
adapter.SelectCommand.Parameters.AddWithValue("#textKeterangan","%" + textKeterangan + "%");
Not sure if your field textKeterangan value should be textKeterangan.Text or textKeterangan. You can take care of this.
Related
I am trying to delete a record in my database table. I am trying to delete it on the basis of a selected name in the dropdown list. When I debug my code there is not any record available in dataset and an exception "invalid column name" occurs, whereas if I run the same query in SQL Server, everything seems to be fine.
This is my code:
protected void SubCategory_Delete_Click(object sender, EventArgs e)
{
try
{
var conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = ' ' "+ DropDownList2.SelectedItem.Value, conn);
var ds = new DataSet();
adpt.Fill(ds, "tc_prod_subcategory");
foreach (DataRow dr in ds.Tables["tc_prod_subcategory"].Rows)
{
dr.Delete();
}
SqlCommandBuilder build = new SqlCommandBuilder(adpt);
adpt.Update(ds, "tc_prod_subcategory");
Updatesubcategorygrid();
updatedelete_dropdown();
Lblsub_catdelete.Text = "Deleted Successfully";
}
catch(Exception ex)
{
Lblsub_catdelete.Text = ex.Message;
}
}
And this is the same query when I run it in SQL Server 2014; everything runs fine:
Select *
from tc_prod_subcategory
Where subcategory_name= 'Favicon'
The error is caused by the incorrect position of the apostophes in the where clause. It should be like:
"Select * from tc_prod_subcategory where subcategory_name = '" + DropDownList2.SelectedItem.Value + "'"
but that code is vulnerable to a SQL injection,so you should use parameters instead of concatenating strings.
var conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = #subcategory_name", conn);
var ds = new DataSet();
adpt.SelectCommand.Parameters.AddWithValue("#subcategory_name", DropDownList2.SelectedItem.Value);
If you use c# version >= 6.0
you can use interpolation to concat strings in very handy and less error-prone way.
var adpt = new SqlDataAdapter($"Select * from tc_prod_subcategory where subcategory_name = '{DropDownList2.SelectedItem.Value}'", conn);
I received this Exception while executing Select query:-
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code .The multi-part identifier "sd.MED_ID" could not be bound.
My Code is
connection conec = new connection();
SqlDataAdapter sqlDataAdapter ;
SqlCommandBuilder sqlCommandBuilder ;
DataSet ds;
private void set_data_Click(object sender, EventArgs e)
{
conec.conopen();
//string query="Select S_ID as 'SYMPTOM NO',SD_ID as 'DISK NO',MED_ID as 'MED NAME',SRO,PNR,SYM as '% SYM',DMD from SYM_DETAIL";
sqlDataAdapter = new SqlDataAdapter("Select SY_DID,S_ID as 'SYMPTOM NO',SD_ID as 'DISK NO',m.med_name as 'MED NAME',SRO,PNR,SYM as '% SYM',DMD from SYM_DETAIL sd"+
"inner join MEDICINE m on sd.MED_ID=m.med_Id where sd.S_ID="+txtbxsymid_update.Text+" and sd.SD_ID="+txtbxdiskid_update.Text+"", conec.con);
ds = new System.Data.DataSet();
sqlDataAdapter.Fill(ds, "SYM_DETAIL");
dataGridView1.DataSource = ds.Tables[0];
Here is what's causing this error:
from SYM_DETAIL sd"+
"inner join MEDICINE
You are missing a space between sd and inner, so the alias becomes sdinner.
Another, more serious problem is that you are concatenating strings to create your SQL statement. This is a security hazard as it's an open door for SQL injection attacks.
To remove the threat you need to use parameters in your query, so you must use an SqlCommand instance.
Also, you should note that SqlConnection, SqlCommand and SqlDataAdapter all implements the IDisposable interface, so you should wrap them in a using statement.
I don't know what's the connection class in your code but from what I see it contains SqlConnection inside. I would not recommend using SqlConnection like this since SqlConnection should be closed and disposed to return to the connection pool.
Here is how I would suggest writing this code:
// a class member
private string connectionString;
// In your constructor
connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
private void set_data_Click(object sender, EventArgs e)
{
var ds = new DataSet();
var query = "Select SY_DID, S_ID as 'SYMPTOM NO', SD_ID as 'DISK NO', m.med_name as 'MED NAME', SRO, PNR, SYM as '% SYM', DMD" +
" from SYM_DETAIL sd" +
" inner join MEDICINE m on sd.MED_ID=m.med_Id" +
" where sd.S_ID = #S_ID" +
" and sd.SD_ID= #SD_ID";
using(var con = new SqlConnection(connectionString)
{
using(var cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#S_ID", SqlDbType.VarChar).Value = txtbxsymid_update.Text;
cmd.Parameters.Add("#SD_ID", SqlDbType.VarChar).Value = txtbxdiskid_update.Text;
using(var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds, "SYM_DETAIL");
}
}
}
dataGridView1.DataSource = ds.Tables[0];
}
I'm pretty new in c#, taking lessons but with what i'm trying to do i know that i'm way ahead of schedule.
I have a form with a listbox and a textbox.
this is how I populate the listbox
private void Centrale_Gegevens_Load(object sender, EventArgs e)
try
{
OleDbConnection verbinding = new OleDbConnection();
verbinding.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\Het Vlaamse Kruis\Het Vlaamse Kruis\data\Patienten.accdb; Jet OLEDB:Database Password=internet;";
verbinding.Open();
OleDbCommand combo = new OleDbCommand();
combo.Connection = verbinding;
string query = "select NaamPatient from tbl_Patient";
combo.CommandText = query;
OleDbDataReader reader = combo.ExecuteReader();
while (reader.Read())
{
lstBox.Items.Add(reader["NaamPatient"]);
}
verbinding.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
the listbox is in that way populated with names of persons.
The textbox named textbox1 is what i want to use to filter the listbox.
This is what i got sofare, but it doesn't work.
private void textBox1_TextChanged(object sender, EventArgs e)
{
OleDbConnection verbinding = new OleDbConnection();
verbinding.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\Het Vlaamse Kruis\Het Vlaamse Kruis\data\Patienten.accdb; Jet OLEDB:Database Password=internet;";
verbinding.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_Patienten where NaamPatient like '" + textBox1.Text + "%' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
lstBox.DataSource = dt;
lstBox.DisplayMember = "NaamPatient";
verbinding.Close();
}
I have red almost everything I can find on the net about it, bus no mather what i do, I can't get it to work.
How can I get if I type A in the textbox that the listbox shows all the names beginning with A, And if I type AB that the listbox shows everything beginning with AB etc.
Thanks in advance
Firstly, in Centrale_Gegevens_Load, table's name is tbl_Patient but in textBox1_TextChanged, it is tbl_Patienten.
Secondly,Connection property has not been initialized.
you must insert this: cmd.Connection = verbinding; after initializing the cmd;
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = verbinding;
Sorry for my bad English.
I get Oledb exception
private void Form5_Load(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\cus1.mdb");
ada = new OleDbDataAdapter("select ubal from cus1 where uname="+this.label3.Text,con);
ds = new DataSet();
//OleDbCommand cmd = new OleDbCommand("SELECT ubal FROM cus1 WHERE uname=#uname");
//ocb = new OleDbCommandBuilder(ada);
//textBox2.Text = label3.Text;
ada.Fill(ds,"cus1");
textBox1.DataBindings.Add("Text", ds, "cus1.ubal");
bm = this.BindingContext[ds.Tables[0]];
// cmd.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
}
how to solve this?
You are missing single quotes around your text. But to avoid a whole boat load of problems regarding your sql queries, including sql injection, always use parameters:
ada = new OleDbDataAdapter("select ubal from cus1 where uname=?", con);
ada.SelectCommand.Parameters.AddWithValue("?", this.label3.Text);
This is my code:
This is in a different class named DBAccess
public DataSet getRecords(DateTime dtpFloor,DateTime dtpCeiling)
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = " SELECT * FROM dbo.ClientInvoice WHERE invDate BETWEEN '" + dtpCeiling + "' AND '" + dtpFloor + "'";
SqlDataAdapter da = new SqlDataAdapter(newCmd);
DataSet dsIncome = new DataSet();
da.Fill(dsIncome, "Client");
conn.Close();
return dsIncome;
}
Below Coding is in the ProfitLos form class
public void btnClickFillGrid()
{
DataSet dsIncome = dba.getRecords(dtpFloor.Value.ToString(), dtpCeiling.Value.ToString()); //dba is an object of DBAccess class
dgvproIncome.DataSource = dsIncome.Tables["Client"].DefaultView;
}
btnClickFillGrid() will invoke at the button click event.
In the database - invdate datetime;(invDate is the variable name and its in the datetime format)
i edited my coding like this
public DataSet getRecords(DateTime dtpFloor,DateTime dtpCeiling)
{
using (SqlConnection conn = new SqlConnection("Data Source=KOSHITHA-PC;Initial Catalog=ITP;Integrated Security=True"))
{
conn.Open();
using (SqlCommand command = conn.CreateCommand())
{
string sql = "SELECT * FROM dbo.ClientInvoice WHERE invDate BETWEEN" + "#from AND #to";
command.CommandText = sql;
command.Parameters.AddWithValue("#from",dtpFloor);
command.Parameters.AddWithValue("#to", dtpCeiling);
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet dataSetClient = new DataSet();
da.Fill(dataSetClient, "Client");
return dataSetClient;
}
}
}
DataSet dataSetClient = dba.getRecords(dtpFloor.Value, dtpCeiling.Value);
dgvproIncome.DataSource = dataSetClient.Tables["Client"].DefaultView;
now i m getting an exception in "da.Fill(dataSetClient, "Client");" line saying
sqlException was unhandled
An expression of non-boolean type specified in a context where a condition is expected, near 'BETWEEN#from'.
i m not familiar with the parameter passing method to sql query,so couldnt find the problem that i m having
Look at this call:
dba.getRecords(dtpFloor.Value.ToString(), dtpCeiling.Value.ToString());
That's clearly passing in strings as the arguments. Now look at your method declaration:
public DataSet getRecords(DateTime dtpFloor,DateTime dtpCeiling)
Those parameters are of type DateTime, not string. So the first thing to fix is the call, to:
dba.getRecords(dtpFloor.Value, dtpCeiling.Value);
Now the next problem is that you're embedding the values in the SQL directly. Don't do that. Never do that. In some cases it can lead to SQL injection attacks, and in other cases it causes data conversion issues (as you've got here). Use parameterized SQL instead - oh, and use connection pooling rather than trying to use a single connection in multiple places:
public DataSet GetRecords(DateTime dtpFloor,DateTime dtpCeiling)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand command = conn.CreateCommand())
{
string sql = "SELECT * FROM dbo.ClientInvoice WHERE invDate BETWEEN "
+ "#from AND #to";
command.CommandText = sql;
command.Parameters.AddWithValue("#from", dtpFloor");
command.Parameters.AddWithValue("#to", dtpCeiling");
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
da.Fill(dataSet, "Client");
return dataSet;
}
}
}