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];
}
Related
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.
This situation often I met when my query is too long. I have defined parameter #no_registrasi, but it still error.
MySql.Data.MySqlClient.MySqlException: Fatal error encountered during command execution. ---> MySql.Data.MySqlClient.MySqlException: Parameter '#no_registrasi' must be defined.
Here is my code:
void Tombol_cari_simpanan1Click(object sender, EventArgs e)
{
string connectionString = "Server=localhost;User ID=root;Password=;Database=koperasi;Convert Zero Datetime=True;";
MySql.Data.MySqlClient.MySqlConnection connect = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
connect.Open();
string query = "select * from simpanan left join anggota on simpanan.no_registrasi = anggota.no_registrasi left join jenis_simpanan on simpanan.id_jenis_simpanan = jenis_simpanan.id_jenis_simpanan where simpanan.no_registrasi = #no_registrasi";
MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(query, connect);
myCommand.Parameters.AddWithValue("#no_registrasi", int.Parse(textbox_pencarian_no_registrasi.Text));
MySql.Data.MySqlClient.MySqlDataReader reader=myCommand.ExecuteReader();
connect.Close();
mySqlDataAdapter = new MySql.Data.MySqlClient.MySqlDataAdapter(query, connect);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
datagrid_simpanan.DataSource = DS.Tables[0];
connect.Close();
}
Because you add the parameter in MySqlCommand myCommand object.
But you also query by mySqlDataAdapter, that object didn't set any parameter.
from your code of part about MySqlCommand myCommand is unnecessary because you didn't use
MySql.Data.MySqlClient.MySqlDataReader reader=myCommand.ExecuteReader();
I guess you can try this.
void Tombol_cari_simpanan1Click(object sender, EventArgs e)
{
string connectionString = "Server=localhost;User ID=root;Password=;Database=koperasi;Convert Zero Datetime=True;";
string query = "select * from simpanan left join anggota on simpanan.no_registrasi = anggota.no_registrasi left join jenis_simpanan on simpanan.id_jenis_simpanan = jenis_simpanan.id_jenis_simpanan where simpanan.no_registrasi = #no_registrasi";
MySql.Data.MySqlClient.MySqlConnection connect = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
connect.Open();
mySqlDataAdapter = new MySql.Data.MySqlClient.MySqlDataAdapter(query, connect);
DataSet DS = new DataSet();
mySqlDataAdapter.SelectCommand.Parameters.AddWithValue("#no_registrasi", int.Parse(textbox_pencarian_no_registrasi.Text));
mySqlDataAdapter.Fill(DS);
datagrid_simpanan.DataSource = DS.Tables[0];
connect.Close();
}
Note:
I would use using keyword to contain
MySqlConnection connect = new MySqlConnection(connectionString)
becasue when connect object leave the scope it will call IDisposable.Dispose() interface method automaticlly.
string connectionString = "Server=localhost;User ID=root;Password=;Database=koperasi;Convert Zero Datetime=True;";
string query = "select * from simpanan left join anggota on simpanan.no_registrasi = anggota.no_registrasi left join jenis_simpanan on simpanan.id_jenis_simpanan = jenis_simpanan.id_jenis_simpanan where simpanan.no_registrasi = #no_registrasi";
DataSet DS = new DataSet();
using (MySqlConnection connect = new MySqlConnection(connectionString))
{
connect.Open();
mySqlDataAdapter = new MySqlDataAdapter(query, connect);
mySqlDataAdapter.SelectCommand.Parameters.AddWithValue("#no_registrasi", int.Parse(textbox_pencarian_no_registrasi.Text));
mySqlDataAdapter.Fill(DS);
datagrid_simpanan.DataSource = DS.Tables[0];
}
Error An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. How to fix it?
Image: http://i.stack.imgur.com/7Sibc.png
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand sc = new SqlCommand("select Title from TongHopDB", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Load(reader);
cboxDB.ValueMember = "Title";
cboxDB.DisplayMember = "Title";
cboxDB.DataSource = dt;
conn.Close();
}
private void cboxDB_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "Select Title, Post from TongHopDB where Title = " + cboxDB.SelectedValue.ToString(); // câu query có thể khác với kiểu dữ liệu trong database của bạn
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader sdr = cmd.ExecuteReader();
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
sdr.Close();
sdr.Dispose();
conn.Close();
conn.Dispose();
}
string sql = "Select Title, Post from TongHopDB where Title = '" + cboxDB.SelectedValue.ToString()+"'";
However I strongly suggest to use parameters:
string sql = "Select Title, Post from TongHopDB where Title = #Title";
cmd.Paramaters.Add( "#Title",cboxDB.SelectedValue.ToString());
I strongly suspect your Title is character typed, that's why it needs to used with single quotes as;
where Title = '" + cboxDB.SelectedValue.ToString() + "'";
But don't use this way.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader objects automatically instead of calling Close or Dispose methods manually.
using(var conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7"))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Title, Post from TongHopDB where Title = #title";
cmd.Parameters.Add("#title", SqlDbType.NVarChar).Value = cboxDB.SelectedValue.ToString();
// I assumed your column type is nvarchar.
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
if(dr.Read())
{
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
}
}
}
cboxDB.SelectedValue is Apple according to the error shown in your screen shot. Your SQL statement is saying in plain English:
Select Title(column) and Post(column) from TongHopDB(table) where Title(column) equals Apple(column)
Apple is not a valid column!
While it would work to simply add single quotes around the value of cboxDB, you should use parameters instead of concatenating a string. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
I have an openquery SQL script:
Select * from openquery([oak],'
SELECT LicenseKey, SUM(PaymentAmount)as Payments
FROM vw_ODBC_actv_Payments pt
WHERE MONTH(pt.EntryDate) = 2 and
YEAR(pt.EntryDate) = 2015
GROUP BY LicenseKey
')
When I run this from SSMS I can see that it returns expected n rows.
However when I'm firing this with the same connection properties to get the data in a DataSet for a C# console application:
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand pcmd= new SqlCommand();
DataSet ds= new DataSet();
OpenConnection();
pcmd.Connection = new SqlConnection("Data source=IP adress of the server;Initial Catalog=master; user ID=***; password=***");
cmd.CommandText = "Select * from openquery([oak],'" +
"SELECT LicenseKey, SUM(PaymentAmount)as Payments" +
"FROM vw_ODBC_actv_Payments pt " +
"WHERE MONTH(pt.EntryDate) = 2 and" +
"YEAR(pt.EntryDate) = 2015" +
"GROUP BY LicenseKey')";
try
{
da.SelectCommand = pcmd;
da.Fill(ds); //here comes the error
}
catch (Exception ex)
{
throw new Exception("DBUtils.ExecuteReader():" + ex.Message);
}
I'm getting an error like this:
The provider indicates that the user did not have the permission to
perform the operation. Now I need to do something with this issue
I'm just learning about openquery. Can anybody guide?
Firstly you're not opening the connection anywhere in your code hence the error. Second clean up your code with the using block. So assuming the query works as required you can do something like.
using(SqlConnection con = new SqlConnection("Connection String Here"))
{
string myQuery = "Your Query";
using(SqlCommand cmd = new SqlCommand(myQuery, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
}
}
}
Note: It would be a better if you stored the connectionString in your config file and read it in your code.
i keep getting this error, i dont know why, im still new to c#. kindly help me figure this out please. i have two dropdownlist that would populate data based on first dropdownlist selected value.
when i select a value on the first dropdownlist, i get that error..
here is my code..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//read sql server connection string from web.config file
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE ="+ddlProvince.SelectedValue, conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlProvince.DataBind();
}
}
It happens because you passed the raw value without quotes, so the database thought you mean field name.
Avoid this all mess by using Parameters:
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE=#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
This answer is an alternative approach, when using Parameters isn't viable.
The SQL interpreter is confusing values with database objects.
You can save the interpreter from confusion by making your SQL statement more explicit. Surround columns and table names with [ square brackets and wrap any values in single quotes.
using (conn)
{
var whereValue = "'"+ddlProvince.SelectedValue+"'";//wrap in single quotes
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [CITY_NAME] FROM [emed_city] WHERE [PROVINCE_CODE] = "+whereValue;
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
The square brackets explicitly state to the SQL Intepreter that it is dealing with a database object. The single quotes inform the interpreter it is dealing with a value.
Now the interpreter won't mistake your value for a column name.