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];
}
Related
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];
}
Hello I have problem on create report with crystal report c#,
I should insert the result of this SqlAdapter in a c # report , but do not know how to do
String Query = "SELECT Utente.LogoAzienda,Preventivo.DataInserimento,Preventivo.RiferimentoInterno,Preventivo.Testata,Preventivo.Chiusura,Cliente.Titolo,Cliente.RagioneSociale,Cliente.Indirizzo,Cliente.Cap,Cliente.Citta,Cliente.Provincia FROM Preventivo inner join Cliente on Cliente.IdCliente = Preventivo.IdCliente inner join Utente on Preventivo.UtenteCreazione = Utente.Username";
SqlConnection conn = db.apriconnessione();
DataStampaPreventivoCompleto d = new DataStampaPreventivoCompleto();
SqlDataAdapter da = new SqlDataAdapter(Query, conn);
da.Fill(d, d.Tables[0].TableName);
Here is an example to bind dataset to crystal report:
private void CrystalFormView_Load(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["sqlbill"].ConnectionString;
string provider = ConfigurationManager.ConnectionStrings["sqlbill"].ProviderName;
SqlConnection con = new SqlConnection(connection);
SqlDataAdapter sda = new SqlDataAdapter("select product as Product,productid as ProductId,quantity as Quantity from productdata", con);
DataSet ds = new DataSet();
sda.Fill(ds);
ds.Tables[0].TableName = "BILLTEST";
BillCrystalReport bill = new BillCrystalReport();
bill.SetDataSource(ds);
bill.VerifyDatabase();
crystalReportViewer1.ReportSource = bill;
crystalReportViewer1.RefreshReport();
}
For more, please check this link: http://www.codeproject.com/Tips/754037/Bind-Crystal-Reports-with-Dataset-or-Datatable
I have created a web page in Asp.net website. The following page load will run as it gets arguments from previous page. The page also has an option for editing the contents and updating in database. But when the button(save) is clicked it doesn't update the database.Kindly help in this. But when there is no connection in page load the update command works.
protected void Page_Load(object sender, EventArgs e)
{
String cust=Request.QueryString["custName"];
String env = Request.QueryString["env"];
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
view();
if (env == "Production")
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value= myRow["Customer_Maintenance"].ToString();
serviceAffect.Value=myRow["Systems/Services_Affected"].ToString();
email_Content.Value= myRow["Email_Content"].ToString();
email_Signature.Value= myRow["Email_Signature"].ToString();
email_From.Value=myRow["Email_From"].ToString();
email_To.Value=myRow["Email_To"].ToString();
email_Cc.Value=myRow["Email_Cc"].ToString();
email_Bcc.Value=myRow["Email_Bcc"].ToString();
}
}
else
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Non_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value = myRow["Customer_Maintenance"].ToString();
serviceAffect.Value = myRow["Systems/Services_Affected"].ToString();
email_Content.Value = myRow["Email_Content"].ToString();
email_Signature.Value = myRow["Email_Signature"].ToString();
email_From.Value = myRow["Email_From"].ToString();
email_To.Value = myRow["Email_To"].ToString();
email_Cc.Value = myRow["Email_Cc"].ToString();
email_Bcc.Value = myRow["Email_Bcc"].ToString();
}
}
The following is the button click for Save Button(for update command)
protected void save_click(object sender, EventArgs e)
{
//Button Click Save
/* String id = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",TextBox1.Text,id);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
*/
String cust = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
if (env.Value == "Production")
{
//String sql = String.Format("Update Customer_Production set Customer_Maintenance='{0}',Environment='{1}',[Systems/Services_Affected]='{2}',Email_Content='{3}',Email_Signature='{4}',Email_To='{5}',Email_Cc='{6}',Email_Bcc='{7}',Email_From='{8}' where Customer_Name like '{9}' ", "custMaintain.Value","env.Value","serviceAffect.Value","email_Content.Value","email_To.Value","email_Cc.Value","email_Bcc.Value","email_From.Value", "cust");
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'", email_Signature.Value,cust);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
}
else
{
}
}
I'm not sure why having a connection (or not) in the Page_Load would make a difference, but here's one thing that looks off to me:
String.Format(
"Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",
email_Signature.Value,
cust);
(I broke it into several lines because the part I'm interested in is the last part of the format string.)
You've set cust to "A" earlier in that method. So the SQL that will result will look (at the end) like this:
... where Customer_Name like 'A'
Unless you have a customer name that is exactly equal to A, that's not going to return anything, and therefore no records will be updated. You're forgetting the '%' wildcard.
I agree with all those who have pointed out that your code is vulnerable to SQL injection (and you'll also have a problem with single quotes), but just to show you what it needs to look like, here it is with the wildcard:
Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}%'
I am getting
"No value given for one and more required parameter"
from below code everything looks fine not able to find the problem.
string myConnectionString= #"Provider=Microsoft.Jet.OLEDB.4.0; Data source=D:\TiptonDB.mdb";
string query = "SELECT NodeID FROM NDDINodes";//"SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
DataSet dt = new DataSet();
using (OleDbConnection myConnection = new OleDbConnection())
{
myConnection.ConnectionString=myConnectionString;
OleDbCommand cmd=new OleDbCommand ();
cmd.Connection=myConnection;
// cmd.CommandText="SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
myConnection.Open();
OleDbDataAdapter ad = new OleDbDataAdapter(query,myConnection);
ad.Fill(dt);
}
string myConnectionString= #"Provider=Microsoft.Jet.OLEDB.4.0; Data source=D:\TiptonDB.mdb";
string query = "SELECT NodeID FROM NDDINodes";//"SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
DataSet dt = new DataSet();
OleDbConnection objXConn = new OleDbConnection(myConnectionString);
objXConn.Open();
OleDbCommand objCommand = new OleDbCommand(query, objXConn);
OleDbDataAdapter adp = new OleDbDataAdapter(objCommand);
adp.Fill(dt);
objXConn.Close();
Make sure your connection string isn't missing data: UserName/Password, Persist Security Info=True,...
Check this link for access connectionString settings.
just add this in your code
OleDbDataAdapter ad = new OleDbDataAdapter();
ad.SelectCommand = new OleDbCommand(query, myConnection);
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.