I have tried search for an ID in an MySQL table and return the associated string column which holds the URL.
But The Downloader always tells me the link format is wrong.
This is my method:
public string URL(string ID)
{
MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=root;database=Downloader;");
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID = '" + ID + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
return reader.ToString();
}
And here the downloader:
private void button1_Click(object sender, EventArgs e)
{
sql_reader sql_reader = new sql_reader();
if (!Directory.Exists("Downloads"));
{
Directory.CreateDirectory("Downloads");
}
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text)), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
textBox1 is the Box where I type in the ID.
1. you need to call Read() function before fetching the records from MySqlDataReader Object
2. you have to specify the column name while accessing the records.
Example:
String result="";
MySqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
result=reader["columnname"].ToString();
3. I would suggest you to use Parametrised Queries to avoid SQL injection Attacks.
Example:
MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =#ID;");
cmd.Parameters.AddWithValue("#ID",ID);
4. dipose the MySqlCommand,MySqlConnection and MySqlDataReader Objects properly. you can use using{} block to dipose them cleanly.
Complete Code
public string URL(string ID)
{
String result="";
using(MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=root;database=Downloader;"))
{
using(MySqlCommand cmd = new MySqlCommand("SELECT string FROM Files WHERE ID =#ID;"))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#ID",ID);
using(MySqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
result=reader["string"].ToString();
else
result="";//you can customize here
}
}
}
return result;
}
Solution 2:
Replace This Statement:
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text)), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
With this:
client.DownloadFileAsync(new Uri(sql_reader.URL(textBox1.Text),UriKind.Absolute), "./Downloads/" + textBox2.Text + "." + textBox3.Text);
Related
I Have a excel and I want Upload only four columns of that to SQL Table with a button.
The problem is when I repeat click the button all of that data will be duplicated but I Don't want that. I want only new data to be update.
My query:
protected void Button1_Click(object sender, EventArgs e)
{
int UserID;
int InsuID;
string Result;
int Year;
//** مسیر فایل اکسل**
String ExcelPath = #"D:\Insu_lab.xlsx";
//** کانکشن به آفیس**
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 cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
UserID = Convert.ToInt32(dr[0].ToString());
InsuID = Convert.ToInt32(dr[1].ToString());
Result = dr[2].ToString();
Year = Convert.ToInt32(dr[3].ToString());
savedata(UserID, InsuID, Result, Year);
Label1.Text = "اطلاعات با موفقیت در دیتابیس ذخیره شد";
}
}
private void savedata(int UserID, int InsuID, string Result, int Year)
{
String query = "insert into tbl_Result(UserID,InsuID,Result,Year) values(" + UserID + ",'" + InsuID + "','" + Result + "','" + Year + "') ";
String mycon = "Data Source=MC6082; Initial Catalog=Insurance; Integrated Security=true";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Solution 1: When you clickedon button, that(button) disable the button.
Button1.disable = true;
When export ended:
Button1.disable = false;
Solution 2: you can use from jquery ajax in this part.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
if (rdr.Read())
{
MessageBox.Show("Company Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtStaffID.Text = "";
txtStaffID.Focus();
}
else
{
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string Query = "insert into PersonsData (StaffID, FullName, Email, Address, Picture) values('" + this.txtStaffID.Text + "','" + this.txtFullname.Text + "','" + this.txtEmail.Text + "','" + this.txtAddress.Text + "',#img)";
if (con.State != ConnectionState.Open)
con.Open();
cm = new SqlCommand(Query, con);
cm.Parameters.Add(new SqlParameter("#img", img));
int x = cm.ExecuteNonQuery();
con.Close();
MessageBox.Show(x.ToString() + "Successfully Saved!");
}
}
catch (Exception ex)
{
con.Close();
MessageBox.Show(ex.Message);
}
}
This is my code i don't understand why I'm getting this error:
ExecuteReader:Connection Property has not been initialized.
I'm making a save button where the Staffid will be checked first if already.
Before executing the command, you need to say which connection is to be used. In your case, it is:
cm.Connection = con;
Take a note that, include this line of code after opening the connection and after creating the instance of SqlCommand.
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
cm.Connection = con; //Assign connection to command
You didn't assign connection to SqlCommand used in the reader
The error message is clear enough, You have to assign the connection for the Command, either through assignement or through the constructor, That is:
cm = new SqlCommand(CheckID);
cm.Connection = con; // Should be added
SqlDataReader rdr = cm.ExecuteReader();
Or else you can use the constructor to initialize the command like this:
cm = new SqlCommand(CheckID,con);
Hope that you are aware of these things since you ware used it correctly in the else part of the given snippet
Make sure that you assign the SqlConnection to your Command-Object. You can do this via Constructor or Property:
con = new SqlConnection(//Your Connectionstring)
//assign via Constructor
cm = new SqlCommand(CheckID, con);
//or via Property
cm.Connection = con;
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
Further I would recommend you to use a using-block to make sure that the Command and Connection gets destroyed after using it.
using (var con = new SqlConnection())
{
using (var cm = new SqlCommand())
{
}
}
I have a FileUpload control and when I don't insert an image, I want to insert DBNull into the database. So far I have only errors with DBNull.Value. The table allow null for column ImageData.
Here is the code:
protected void button_sign_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
string Image = "~/userimage/" + str.ToString();
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username, #Email, #Password, #ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", Image);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
}
else
{
lblMsg.Text = "Error";
}
}
This should be enough
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? Image: DbNull.Value);
Also refactor your code a little bit:
string image = "";
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
image = "~/userimage/" + str.ToString();
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String connString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? image: DbNull.Value);
con.Open();
cmd.ExecuteNonQuery();
}
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
Don't start your variables with UpperCase letters.
If you set the value of Image at the beginning the rest of the code could stay generic.
protected void button_sign_Click(object sender, EventArgs e)
{
object Image;
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
Image = "~/userimage/" + str.ToString();
}
else {
Image = System.DBNull.Value;
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
using(SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con))
{
// pick the appropriate SqlDbType type for each parameter
cmd.Parameters.Add(new SqlParameter("#Username", SqlDbType.VarChar){Value = name});
cmd.Parameters.Add(new SqlParameter("#Email", SqlDbType.VarChar){Value = email});
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar){Value = pass});
cmd.Parameters.Add(new SqlParameter("#ImageData", SqlDbType.VarChar){Value = Image});
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
Some other notes though
You should specify the Database types using the SqlDbType in your parameters to make sure that the values are translated correctly by the ado.net code.
Wrap you Command in a using block as well
No need to close the connection, the using block will handle that for you.
Do not store passwords in clear text. Instead store a salted hash of the password.
These are the values i want to send to the data base
private void radButton1_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;";
string Query = "insert into rhms.reservation(no_table)values('" + this.comboBox1.SelectAll() + "');";
MySqlConnection condatabase = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand(Query, condatabase);
MySqlDataReader myread;
try
{
condatabase.Open();
myread = cmd.ExecuteReader();
MessageBox.Show("saved");
this.Refresh();
while (myread.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need set correct info at query string. Now it`s incorrect. Data must separated by commas:
string Query = "insert into rhms.reservation(no_table) values " + this.comboBox1.Items
.Select(p=>string.Format("({0})",p.ToString()))
.Aggregate((p1,p2)=>p1 + "," + p2) + ";"
I want to perform 2 queries in one button click. I tried the
string query = "first query";
query+="second query";
But this didn't work it shows error.
I have now created 2 separate connections like below:
try
{
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
//open connection with database
conn1.Open();
//query to select all users with teh given username
SqlCommand com1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", conn1);
// comand.Parameters.AddWithValue("#id", iD);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute queries
com1.ExecuteNonQuery();
conn1.Close();
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com2 = new SqlCommand("insert into artikulli(path) values ('" + filename + "')", conn2);
//open connection with database
conn2.Open();
com2.ExecuteNonQuery();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni perzgjedhur asnje file');", true);
}
}
But the problem is that only the second query is performed and the firs is saved as null in database
In your case, there is no reason to open two connections. In addition, the C# language has evolved, so I recommend using the power given by the new language constructs (using, var).
Here is an improved version that should work assuming that the values you bind to your parameters are valid:
try
{
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString))
{
//open connection with database
connection.Open();
//query to select all users with teh given username
using(var command1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", connection))
{
command1.Parameters.AddWithValue("#tema", InputTitle.Value);
command1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
command1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
command1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute first query
command1.ExecuteNonQuery();
}
//build second query
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
using(SqlCommand command2 = new SqlCommand("insert into artikulli(path) values (#filename)", connection))
{
//add parameters
command2.Parameters.AddWithValue("#filename", filename);
//execute second query
command2.ExecuteNonQuery();
}
}
}
//TODO: add some exception handling
//simply wrapping code in a try block has no effect without a catch/finally
Try below code, No need to open the connection twice
string query1 = "insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com1= new SqlCommand(query1, conn);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
string query2 = "insert into artikulli(path) values ('" + filename + "')", conn);
comm.ExecuteNonQuery();
comm.CommandText = query2;
comm.ExecuteScalar();