i have this code, but it doesn't work
try
{
con.Open();
using (SqlCommand command = new SqlCommand("select nev, telefonszam, felhasznalonev, lakcim,email from Felhasznalo where felhasznalonev='"+cbUsername.Text+"' ", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString(0);
string phone = reader.GetInt32(1).ToString();
string username = reader.GetString(2);
string address = reader.GetString(3);
string email = reader.GetString(4);
tbUsername.Text = username;
tbName.Text = name;
//tbPhoneNumber.Text = phoneNumber.ToString();
tbAddress.Text = address;
tbEmail.Text = email;
}
}
}
catch (Exception ex)
{
MessageBox.Show(""+ex);
}
finally
{
con.Close();
}
the error is: Specified cast is not valid.
What is wrong?
i got the solution from here:https://www.youtube.com/watch?v=sKealDA-Wr8
I would suggest that you do this for all the fields that you are returning.
string phone = (string)reader["telefonszam"].ToString();
What if the Database structure changes or you add new columns and change the index / order.. using GetString(4) for example would be fail if the datatype in that column position were to change that is why I recommended that you use the actual column names.
Related
I have a table with three columns
MyDate : DateiIme
MyBlob: blob
Id: String
I want to return MyDate and MyBlob as Json. There can be multiple records in the table.
public class MyData
{
public string? MyDate { get; set; };
public string? MyBlob { get; set; };
}
public async Task<string> GetQueryResult(string Id)
{
MyData data = new MyData();
List<MyData> MyList = new List<MyData>();
string sqlSelect = string.Format("Select MyDate, MyBlob from MyTablee WHERE Id = '{0}'", Id);
try
{
MySqlCommand sqlcmd = new MySqlCommand();
MySqlConnection connetcion = new MySqlConnection(connectionString);
sqlcmd.Connection = connetcion;
sqlcmd.CommandTimeout = 0;
sqlcmd.CommandType = CommandType.Text;
sqlcmd.CommandText = sqlSelect;
connetcion.Open();
using (connetcion)
{
int count = 0;
using (MySqlDataReader reader = sqlcmd.ExecuteReader())
{
while (reader.Read())
{
data.MyDate = reader.GetString(0);
data.MyBlob = reader.GetString(1);
MyList.Add(data);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
var json = JsonSerializer.Serialize(results);
return json;
}
The output in the Postman is:
"{\"MyDate\":\"1/30/2023 9:16:40 PM\",\"MyBlob\":\"#MyBlob\"}"
I am not sure the blob data to JSON conversion is correct. Thank you.
It's probable that your table doesn't contain any BLOB data, but instead contains the literal string #MyBlob in that column.
The cause of this would be using a SQL statement like INSERT INTO MyTablee(MyDate, MyBlob) VALUES(NOW, '#MyBlob');, which inserts the literal text #MyBlob.
Make sure your insert code is constructed as follows:
using var command = connection.CreateCommand();
command.CommandText = "INSERT INTO MyTablee(MyDate, MyBlob) VALUES(NOW(), #blob);";
command.Parameters.AddWithValue("#blob", yourBlobDataHere);
command.ExecuteNonQuery();
In particular, there are no quotes around the parameter name in the INSERT statement, and command parameters are being used to send values, instead of string concatenation.
I trying to update a GridView using asp.net while updating I am passing the text box value but I am getting the above error.
Label l1 = g1.Rows[e.RowIndex].FindControl("idlbl") as Label;
TextBox t1 = g1.Rows[e.RowIndex].FindControl("typeText") as TextBox;
string orderType = t1.Text;
string Query = #"update app_order_master set order_amt=" + orderType + " where order_id=" + l1.Text;
MySqlCommand cmd = new MySqlCommand(Query);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
Try using parameters instead
Label l1 = g1.Rows[e.RowIndex].FindControl("idlbl") as Label;
TextBox t1 = g1.Rows[e.RowIndex].FindControl("typeText") as TextBox;
string orderType = t1.Text;
string order_id = l1.Text;
string Query = "update app_order_master set order_amt = #orderType where order_id = #order_id";
MySqlCommand cmd = new MySqlCommand(Query);
cmd.Parameters.Add("#orderType", orderType);
cmd.Parameters.Add("#order_id", order_id);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
Here is another example that might help you, a pointer that other developers have mentioned your original code is a probe to SQL injection if you bing search this, there are loads of examples that you can find of what SQL injection is. Here is my method that might assist you. A little code example to assist you.
public void updateProductTbl(string prodBrand, string description, decimal weight, decimal unitwholesaleprice, decimal unitretailprice, string prodImage, string location, string qrcode,
string barcode, string suppliercode, int unitinstock, int unitsonorder, int reorderlevel, bool discontinued, decimal unitofmeasure, string prodcategory, int OldValue)
{
query = #"update Product
SET
prod_band=#prodBrand
,prod_description=#description
,prod_weight=#weight
,prod_perUnitwholesalePrice=#unitwholesaleprice
,prod_perUnitRetailPrice = #unitretailprice
,prod_Image=#prodImage
,prod_location=#location
,prod_QRcode=#qrcode
,prod_barcode=#barcode
,prod_supplierFKCode=#suppliercode
,prod_unitsinstock=#unitinstock
,prod_unitsonorder=#unitonorder
,prod_reorderlevel=#reorderlevel
,prod_discontinued=#discontinued
,prod_unitofmeasure=#unittofmeasure
,prod_category=#prodcategory
where prod_rec_id=#OldValue";
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(query, myConn);
myCommand.Parameters.AddWithValue("#prodBrand", prodBrand);
myCommand.Parameters.AddWithValue("#description", description);
myCommand.Parameters.AddWithValue("#weight", weight);
myCommand.Parameters.AddWithValue("#unitwholesaleprice", unitwholesaleprice);
myCommand.Parameters.AddWithValue("#unitretailprice", unitretailprice);
myCommand.Parameters.AddWithValue("#prodImage", prodImage);
myCommand.Parameters.AddWithValue("#location", location);
myCommand.Parameters.AddWithValue("#qrcode", qrcode);
myCommand.Parameters.AddWithValue("#barcode", barcode);
myCommand.Parameters.AddWithValue("#suppliercode", suppliercode);
myCommand.Parameters.AddWithValue("#unitinstock", unitinstock);
myCommand.Parameters.AddWithValue("#unitonorder", unitsonorder);
myCommand.Parameters.AddWithValue("#reorderlevel", reorderlevel);
myCommand.Parameters.AddWithValue("#discontinued", discontinued);
myCommand.Parameters.AddWithValue("#unittofmeasure", unitofmeasure);
myCommand.Parameters.AddWithValue("#prodcategory", prodcategory);
myCommand.Parameters.AddWithValue("#OldValue", OldValue);
status = myCommand.ExecuteNonQuery(); // when ExecuteNonQuery method return 1 or 0 if it have saved to sql db
if (status > 0)
{
MessageBox.Show("Your Data has been updated", "Update Data", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch(Exception ex)
{
MessageBox.Show("SQL Error in Product Add method:"+ex.ToString(), "Warning Data not saved", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
myConn.Close();
}
}
Hope the abe gives you a good idea of how to go about SQl and passing params in a method.
I have an upload button that can upload excel file and save it to my database. What I want to happen is that if there's one or more data in that excel file that already existing the other data will also not be uploaded though it's not yet existing. My code for adding it to the database and upload button are below.
Add to database
private void AddNewTrainee(string strdelname, string strrank, string strcomp, string strcourse, string strcenter, string strinst,
string strsdate, string stredate, string strcissued, string strcnumber, string strremark, int recdeleted, string credate, string update, int fromupload)
{
connection.Open();
String checkDateAndName = "Select count(*) from Trainees where StartDate= '" + strsdate + "' and Delegate='" + strdelname + "' and REC_DELETED = 0 ";
SqlCommand cmd = new SqlCommand(checkDateAndName, connection);
int dataRepeated = Convert.ToInt32(cmd.ExecuteScalar().ToString());
bool boolDataRepated;
connection.Close();
if (!(dataRepeated >= 1))
{
boolDataRepated = false;
}
else
boolDataRepated = true;
connection.Open();
string certNumber = "Select * from CertID_Table update CertID_Table set CertificateID = CertificateID + 1 from CertID_Table ";
SqlCommand cmdCert = new SqlCommand(certNumber, connection);
using (SqlDataReader oReader = cmdCert.ExecuteReader())
{
while (oReader.Read())
{
string test1 = oReader["CertificateID"].ToString();
ViewState["certnumber"] = test1;
}
}
connection.Close();
strcnumber = (string)ViewState["certnumber"];
if (boolDataRepated == false)
{
string path = "D:\\Intern\\BASSWeb\\SQLCommands\\AddSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
try
{
connection.Open();
SqlCommand cmd1 = new SqlCommand(sql, connection);
cmd1.Parameters.AddWithValue("#delName", strdelname);
cmd1.Parameters.AddWithValue("#rank", strrank);
cmd1.Parameters.AddWithValue("#comp", strcomp);
cmd1.Parameters.AddWithValue("#course", strcourse);
cmd1.Parameters.AddWithValue("#center", strcenter);
cmd1.Parameters.AddWithValue("#instructor", strinst);
cmd1.Parameters.AddWithValue("#sdate", strsdate);
cmd1.Parameters.AddWithValue("#edate", stredate);
cmd1.Parameters.AddWithValue("#cissued", strcissued);
cmd1.Parameters.AddWithValue("#cnumber", strcnumber);
cmd1.Parameters.AddWithValue("#remark", strremark);
cmd1.Parameters.AddWithValue("#rdeleted", recdeleted);
cmd1.Parameters.AddWithValue("#cdate", credate);
cmd1.Parameters.AddWithValue("#udate", update);
cmd1.Parameters.AddWithValue("#fupload", fromupload);
cmd1.CommandType = CommandType.Text;
cmd1.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
}
else
{
string script = "alert(\"The data already exists\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
Upload Button
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/Datas/") + path);
String ExcelPath = Server.MapPath("~/Datas/") + path;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmdX = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmdX.ExecuteReader();
while (dr.Read())
{
delegateName = dr[0].ToString();
rankPos = dr[1].ToString();
company = dr[2].ToString();
courseTitle = dr[3].ToString();
trainingCenter = dr[4].ToString();
instructor = dr[5].ToString();
staDa = DateTime.Parse(dr[6].ToString());
string startDate = staDa.ToString("MM/dd/yyyy");
endDa = DateTime.Parse(dr[7].ToString());
string endDate = endDa.ToString("MM/dd/yyyy");
certIssued = dr[8].ToString();
certNum = dr[9].ToString();
remarks = dr[10].ToString();
recDeleted = 0;
dateCreated = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
dateUpdated = string.Empty;
fromUpload = 1;
AddNewTrainee(delegateName, rankPos, company, courseTitle, trainingCenter, instructor,
startDate, endDate, certIssued, certNum, remarks, recDeleted, dateCreated, dateUpdated, fromUpload);
}
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: " + ex.Message.ToString() + " \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
else
{
string errorMessage = "alert(\"ERROR: You have not specified a file \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
PopulateData();
}
You have to set the transferMode to 'Streamed', otherwise you will always get one file.
Have a look at this article: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-enable-streaming
I think there is a few things you'll need to tackle to reach your end goal.
Use a multiselect method and a get a post list of all files required
for upload.
Do your processing requirements in a Transaction
When your done processing, commit or rollback the transaction as necessary and keep the data you want.
Study the link I posted a little bit. At first transaction seem a little bit overwhelming, but they are actually very simple. Maybe I can help you get started in your understandings. There are really only three extra steps;
1.
Initialize a transaction object after you create a command.
SqlTransaction transaction = connection.BeginTransaction();
2.
On all of your Sql Commands (Inserts,updates, deletes ect) attach the transaction.
cmd.Transaction = transaction;
This will allow you to Execute the SqlCommands without actually putting them into your database. Lastly, when you've processed all of your inserts and updates you can do the final step. The using statement is not required, just good practice. That could be the next thing you'll want to understand it is very helpful.
3.
Commit all SqlCommands to the database.
transaction.Commit();
If at any point during your data processing, something goes wrong than you can rollback every transaction like this.
transaction.Rollback();
I would like to find a way to exit out of datareader after the if statement so that I can execute the insert query in else statement. Is there a way to do it?
I am getting the error that dr is still open and hence cannot perform the below query.
sVendorDetails.VendorID = insertcmd.ExecuteNonQuery();
Here is the code:
public class VendorDetails
{
int _VendorID;
string _VendorName;
public int VendorID
{
set { _VendorID = value; }
get { return _VendorID; }
}
public string VendorName
{
set { _VendorName = value; }
get { return _VendorName; }
}
}
public VendorDetails VendorCheck(string sVendorName)
{
SqlCommand cmd = new SqlCommand("dbo.usp_GetVendorByVendorName", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
cmd.Parameters["#VendorName"].Value = sVendorName;
VendorDetails sVendorDetails = null;
try
{
myConnection.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
sVendorDetails = new VendorDetails();
sVendorDetails.VendorID = ((int)dr["VendorID"]);
sVendorDetails.VendorName = ((string)dr["VendorName"]).ToUpper().Trim();
}
}
else if (dr.HasRows!= true)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('VendorName:" + sVendorName + " not found. Inserting Vendor details into Vendor and Invoice table.')", true);
SqlCommand insertcmd = new SqlCommand("dbo.InsertVendorName", myConnection);
insertcmd.CommandType = CommandType.StoredProcedure;
insertcmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
insertcmd.Parameters["#VendorName"].Value = sVendorName;
sVendorDetails = new VendorDetails();
sVendorDetails.VendorID = insertcmd.ExecuteNonQuery();
sVendorDetails.VendorName = sVendorName;
}
dr.Close();
return sVendorDetails;
}
catch (SqlException err)
{
throw new ApplicationException("DB usp_GetVendorByVendorName Error: " + err.Message);
}
finally
{
myConnection.Close();
}
}
You will need to close/dispose of your DataReader prior to reusing the connection, as it's still being used.
Maybe something like this?
var readerHasRows = false;
using (var dr = cmd.ExecuteReader())
{
readerHasRows = dr.HasRows;
if(readerHasRows)
{
while (dr.Read())
{
sVendorDetails = new VendorDetails();
sVendorDetails.VendorID = ((int)dr["VendorID"]);
sVendorDetails.VendorName = ((string)dr["VendorName"]).ToUpper().Trim();
}
}
}
if(!readerHasRows)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('VendorName:" + sVendorName + " not found. Inserting Vendor details into Vendor and Invoice table.')", true);
SqlCommand insertcmd = new SqlCommand("dbo.InsertVendorName", myConnection);
insertcmd.CommandType = CommandType.StoredProcedure;
insertcmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
insertcmd.Parameters["#VendorName"].Value = sVendorName;
sVendorDetails = new VendorDetails();
VendorDetails.VendorID = insertcmd.ExecuteNonQuery();
sVendorDetails.VendorName = sVendorName;
}
There are a few things I would like to mention
Your main issue is that you are not closing your DataReader. You can use the using statement for it
You don't need to explicitly open and close the SqlConnection. The SqlCommand object will do it as needed.
You don't need to check with if (dr.HasRows) and then check again in while (dr.Read()). Also, you don't need to loop to pick up only one row of data.
Ideally, I would put the "Fetch" part in a separate function and the "insert" in a separate function, so the functions stay small and reusable.
Your pattern is superfluous if (flag) {TakeAction();} else if (!flag) {TakeAction2();}. Every time the code hits theelse, it will also hit theif (!flag)`
sVendorDetails.VendorID = insertcmd.ExecuteNonQuery(); line looks fishy. If your Stored Procedure returns the VendorId, then you should use ExecuteScalar. Currently it is just storing 1 in all case since you are presumably inserting one row.
Don't discard the original SqlException when creating a custom ApplicationException. Upstream system might want to know more details than you are passing. Pass it along as the InnerException
I have also changed some stylistic aspects:
The variable names changed to the more commonly used camelCase, instead of the incorrectly used Hungarian Notation (sVendorDetails instead of oVendorDetails)
Brace in K&R style
Used var when the right side is a new statement
Use Object Initializers instead of creation+assignment
Below is the code
public VendorDetails VendorCheck(string vendorName, SqlConnection myConnection) {
try {
return GetVendor(vendorName, myConnection) ?? InsertVendor(vendorName, myConnection);
} catch (SqlException err) {
throw new ApplicationException("DB usp_GetVendorByVendorName Error: " + err.Message, err);
}
}
VendorDetails GetVendor(string vendorName, SqlConnection myConnection) {
using (var cmd = new SqlCommand("dbo.usp_GetVendorByVendorName", myConnection)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
cmd.Parameters["#VendorName"].Value = vendorName;
using (SqlDataReader dr = cmd.ExecuteReader()) {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('VendorName:" + vendorName + " not found. Inserting Vendor details into Vendor and Invoice table.')", true); // TODO: Does this really belong here!?!?
if (dr.Read()) {
return new VendorDetails {
VendorID = ((int)dr["VendorID"]),
VendorName = ((string)dr["VendorName"]).ToUpper().Trim()
};
}
}
}
return null;
}
VendorDetails InsertVendor(string vendorName, SqlConnection myConnection) {
using (var insertcmd = new SqlCommand("dbo.InsertVendorName", myConnection)) {
insertcmd.CommandType = CommandType.StoredProcedure;
insertcmd.Parameters.Add(new SqlParameter("#VendorName", SqlDbType.VarChar));
insertcmd.Parameters["#VendorName"].Value = vendorName;
return new VendorDetails {
VendorID = (int)insertcmd.ExecuteScalar(),
VendorName = vendorName
};
}
}
here is my code:
private void searchInDatabase()
{
MySqlConnection c = new MySqlConnection("datasource=localhost; username=root; password=123456; port=3306");
MySqlCommand mcd;
MySqlDataReader mdr;
String query;
try
{
c.Open();
query = "SELECT * FROM test.classmates WHERE first_name ='"+searchName.Text+"'";
mcd = new MySqlCommand(query, c);
mdr = mcd.ExecuteReader();
if(mdr.Read())
{
firstName.Text = mdr.GetString("first_name");
middleName.Text = mdr.GetString("middle_name");
lastName.Text = mdr.GetString("last_name");
age.Text = mdr.GetString("age");
}
else
{
MessageBox.Show("Result Not Found");
}
}
catch(Exception error)
{
MessageBox.Show("Error: "+error.Message);
}
finally
{
c.Close();
}
}
I would like to ask for a help if I have missed on anything or I am doing it wrong. If you have free time, I will much appreciate it if you will comment the perfect way to do I implement this problem: I want to get data from MySQL then put it in a textbox.
According to MSDN you need to pass the column number as parameter
public override string GetString(int i)
So try to pass the column number (starts from 0) of your column name. Assuming the first_name is the first column of your table then
firstName.Text = mdr.GetString(0);
UPDATE
Try to use MySqlConnectionStringBuilder
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "serverip/localhost";
conn_string.UserID = "my_user";
conn_string.Password = "password";
conn_string.Database = "my_db";
MySqlConnection conn = new MySqlConnection(conn_string.ToString();
First of all look at this sample of connection string and change your connection string:
'Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPasswor;'
If connection is OK send erorr message or full exception.