I am trying to retrieve a blob that i have stored in the database.
I would then like to store it locally on my pc. ive got this far, but i`m stuck for some time now. can anybody helpt me realise this?
private void button1_Click(object sender, EventArgs e)
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
//
MySqlCommand SelectCommand = new MySqlCommand("select template from csharp.members where username='" +
this.user_txt.Text + "' and password = '" +
this.password_txt.Text + "' ; ", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
byte[] tmp = (byte[])(myReader["template"]); // need to save this locally
}
}
Please try this.
File.WriteAllBytes("filename", tmp); // Requires System.IO
Related
I read a string using this format with a data reader. How can I read in a date using similar format?
while (MyReader.Read())
{
TextBox1.Text = (string)MyReader["Note"];
}
Try as given below:
while (MyReader.Read())
{
TextBox1.Text = Convert.ToDateTime(MyReader["DateField"]).ToString("dd/MM/yyyy");
}
in ToString() method you can change data format as per your requirement.
If the query's column has an appropriate type then
var dateString = MyReader.GetDateTime(MyReader.GetOrdinal("column")).ToString(myDateFormat)
If the query's column is actually a string then see other answers.
(DateTime)MyReader["ColumnName"];
OR
Convert.ToDateTime(MyReader["ColumnName"]);
This may seem slightly off topic but this was the post I came across when wondering what happens when you read a column as a dateTime in c#. The post reflects the information I would have liked to be able to find about this mechanism. If you worry about utc and timezones then read on
I did a little more research as I'm always very wary of DateTime as a class because of its automatic assumptions about what timezone you are using and because it is way too easy to confuse local times and utc times.
What I'm trying to avoid here is DateTime going 'oh look the computer I'm being run on is in timezone x, therefore this time must also be in timezone x, when I get asked for my values I'll reply as if I'm in that timezone'
I was trying to read a datetime2 column.
The date time you will get back from sql server will end up being of Kind.Unspecified this seems to mean it gets treated like UTC, which is what I wanted.
When reading a date column you also have to read it as a DateTime even though it has no time and is even more prone to screwing up by timezones (as it is on midnight).
I'd certainly consider this to be safer way of reading the DateTime as I suspect it can probably be modified by either settings in sql server or static settings in your c#:
var time = reader.GetDateTime(1);
var utcTime = new DateTime(time.Ticks, DateTimeKind.Utc);
From there you can get the components (Day, Month, Year) etc and format how you like.
If what you have is actually a date + a time then Utc might not be what you want there - since you are mucking around on the client you may need to convert it to a local time first (depending on what the meaning of the time is). However that opens up a whole can of worms.. If you need to do that I'd recommend using a library like noda time. There is TimeZoneInfo in the standard library but after briefly investigating it, it doesn't seem to have a proper set of timezones. You can see the list provided by TimeZoneInfo by using the method TimeZoneInfo.GetSystemTimeZones();
I also discovered sql server management studio doesn't convert times to local time before displaying them. Which is a relief!
I know that this is an old question, but I'm surprised that no answer mentions GetDateTime:
Gets the value of the specified column as a DateTime object.
Which you can use like:
while (MyReader.Read())
{
TextBox1.Text = MyReader.GetDateTime(columnPosition).ToString("dd/MM/yyyy");
}
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
};
}
OR
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = GetValue<int>(reader["conId"]),
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
};
}
// Base methods
protected T GetValue<T>(object obj)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return default(T);
}
protected T GetValue<T>(object obj, object defaultValue)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return (T)defaultValue;
}
In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Library
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
SqlCommand com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Entry Added");
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr, dr1,dr2;
con.Open();
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
dr1 = com1.ExecuteReader();
dr1.Read();
string i = dr1["BookStatus"].ToString();
if (i =="1" )
{
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
dr2 = com2.ExecuteReader();
dr2.Read();
MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );
}
else
{
con.Close();
con.Open();
dr = com.ExecuteReader();
dr.Read();
MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
}
con.Close();
}
else
{
MessageBox.Show("This Book is not available in the library");
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
con.Open();
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
textBox4.Text = dateofissue;
textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
MessageBox.Show("Book Isuued");
}
else
{
MessageBox.Show("Book Not Found");
}
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
con.Open();
SqlCommand com = new SqlCommand(query1, con);
com.ExecuteNonQuery();
string today = DateTime.Today.ToString("dd-MM-yyyy");
DateTime today1 = DateTime.Parse(today);
string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlDataReader dr;
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
dr = cmd.ExecuteReader();
dr.Read();
string DOR = dr["DateOfReturn"].ToString();
DateTime dor = DateTime.Parse(DOR);
TimeSpan ts = today1.Subtract(dor);
string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
int x = int.Parse(ts.Days.ToString());
if (x > 0)
{
int fine = x * 5;
textBox6.Text = fine.ToString();
MessageBox.Show("Book Received\nFine=" + fine);
}
else
{
textBox6.Text = "0";
MessageBox.Show("Book Received\nFine=0");
}
con.Close();
}
}
}
I have this button click event. Been trying to replace the con.Close() in different lines of code, tried for hours but couldn't fix. Maybe a second pair of eyes can help?
Error: System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.'
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
con.Open();
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
con.Close();
}
else
{
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
con.Open();
int i = cmd1.ExecuteNonQuery();
con.Close();
if (i != 0)
{
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
}
Try this (open connection only once and close only once):
protected void Button1_Click(object sender, EventArgs e) {
using(SqlConnection con = new SqlConnection()) {
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
bool hasRows = reader.HasRows;
reader.Close();
if (hasRows) {
// This line makes no sense after the execution of the query.
//cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
} else {
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
int i = cmd1.ExecuteNonQuery();
if (i != 0) {
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
} else {
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
con.Close();
}
}
Now let's discuss this line
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
This let's attacker manipulate your input with sql injection. To solve this, use the same cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value); that you are using in the second query. The Session["id"] is somewhat safer as it is not provided by the user but better safe than sorry as the parameters sanitize the input and protect you from sql injection.
While my program was normally running in Visual Studio 2017 I closed it and reopened it and from that moment I am getting the error message "System.Data.OleDb.OleDbException: 'Cannot open any more tables.'" in the line with bold letters. My code is connected to a Microsoft Access database. Can you help me, please? It is for my thesis and I am in a real need for your help.
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
label.Content = "Ερώτηση " + Question;
var DBPath = System.AppDomain.CurrentDomain.BaseDirectory + "\\Database\\Users.mdb";
conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + DBPath);
conn.Open();
id = MainWindow.id;
OleDbDataReader dr1 = null;
do
{
rInt = r.Next(1, 20);
cmd = new OleDbCommand("SELECT * FROM TestQuestions WHERE Chapter='Eisagogi' AND ID="+rInt+"; ");
cmd.Connection = conn;
**dr1 = cmd.ExecuteReader();**
Based on your code, I think you are filtering the data from the database by using the radom number.
If you want to use OleDbDataReader to get data from database, I suggest that you use the while(dr1.read()) instead of do.. while.
I modify some code and here is a code example you can refer to.
Code:
var conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + DBPath);
conn.Open();
int rInt = 0;
Random random = new Random();
rInt = random.Next(1, 20);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM TestQuestions WHERE Chapter='Eisagogi' AND ID=" + rInt + "; ",conn);
OleDbDataReader dr1 = cmd.ExecuteReader();
string result = string.Empty;
while(dr1.Read())
{
result = dr1["Question"].ToString();
MessageBox.Show(result);
}
conn.Close();
I want to thank you all for your solutions but the problem was here
OleDbCommand cmd = new OleDbCommand("SELECT * FROM TestQuestions WHERE Chapter='Eisagogi' AND ID=" + rInt + "; ",conn);
I had changed the name Eisagogi in the database so as a result, the 'do...while' command was never finishing.
There was a problem. I checked the connection to the database - everything works.
But when I try to check the lines in the database, then the error pops up:
System.InvalidOperationException: "Connection must be valid and open." c#
How can i fix this?
private void button1_Click(object sender, EventArgs e)
{
try
{
MySqlConnection conn = GetDBConnection();
conn.Open();
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM 'rcc_base' WHERE login='" + this.textBox1.Text + "', pass='" + this.textBox2.Text + "' ;");
MySqlDataReader myReader;
MessageBox.Show("Connection...");
myReader = selectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("All nice");
}
else
{
MessageBox.Show("Login failed");
}
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
In your MySqlCommand you are not using your MySqlConnection :( .So change it as follows
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM rcc_base WHERE 'login' ='" + this.textBox1.Text + "' AND 'pass' ='" + this.textBox2.Text + "' ;",conn);
Also , create a new instance of the MySqlConnection like :
MySqlConnection conn = new MySqlConnection;
conn = GetDBConnection();
And a few suggestions:Your code is not good.Don't give direct values to columns in the SqlCommand rahter pass parameters like #abc , this will also prevent sql-injections.Sample :
MySqlCommand selectCommand = new MySqlCommand("SELECT COUNT(*) FROM rcc_base WHERE login=#username AND pass=#password;",conn);
selectCommand.Parameters.Add("#username",MySqlDbType.VarChar).Value = textBox1.Text;
selectCommand.Parameters.Add("#password",MySqlDbType.VarChar).Value = textBox2.Text;
///Now to check if data exists in the database or not
int count = Convert.ToInt32(selectCommand.ExecuteScalar());
if(count > 0)
{
///data exists-login successful
}
else
{
///data doesn't exists , login failed
}
Also you should open the connection on form load so that you can access the database throughout the class/form.It is a better way to do it :)
i am coding for a commenting system in asp.net C# but i am stopped at delete command because of i am not using any type of serial numbers to comments posted, then how can i able to delete a specific comment, i am just using a username, date, time, and text in comment. Can anyone help me please that how to use a delete command in this condition??
here is my code for posting:
protected void pospost_Click(object sender, EventArgs e)
{
string login;
if (HttpContext.Current.Session["UserName"] != null)
{
login = HttpContext.Current.Session["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from mobiles_pos";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
DataRow rw = ds.Tables[0].NewRow();
rw[0] = Model.Text.ToString();
rw[1] = titlepos.Text.ToString();
rw[2] = txtpos.Text.ToString();
rw[3] = DateTime.Today.Date.ToString();
rw[4] = DateTime.Now.TimeOfDay.ToString();
rw[5] = login.ToString();
ds.Tables[0].Rows.Add(rw);
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into mobiles_pos values('" + Model.Text + "','" + titlepos.Text + "','" + txtpos.Text + "','" + DateTime.Today.Date + "','" + DateTime.Now.TimeOfDay + "','" + login + "')";
da.InsertCommand = cmd1;
da.Update(ds);
con.Close();
titlepos.Text = "";
txtpos.Text = "";
//DataList2.DataSource = ds;
//DataList2.DataBind();
BindDataList2();
}
}
Best - Add a Primary key to the "mobiles_pos" table since your using sql just use an identity field it will auto increment for you.
or
Quick - Use a combination of the User name and date comment was intered you must use the full date time or it will delete everything that user entered that day.
"Delete from mobiles_pos where username = #UserName and createdDate = #createdDate"