This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Upload image to server using C#/.NET and storing filename in DB
How to upload image from a C# application to SQL Server 2005
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
try
{
const string SQL = "INSERT INTO [BinaryTable] ([FileName], [DateTimeUploaded], [MIME], [BinaryData]) VALUES (#FileName, #DateTimeUploaded, #MIME, #BinaryData)";
SqlCommand cmd = new SqlCommand(SQL, Conn);
cmd.Parameters.AddWithValue("#FileName", FileName.Text.Trim());
cmd.Parameters.AddWithValue("#MIME", FileToUpload.PostedFile.ContentType);
byte[] imageBytes = new byte[FileToUpload.PostedFile.InputStream.Length + 1];
FileToUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
cmd.Parameters.AddWithValue("#BinaryData", imageBytes);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
Conn.Open();
cmd.ExecuteNonQuery();
lit_Status.Text = "<br />File successfully uploaded - thank you.<br />";
Conn.Close();
}
catch
{
Conn.Close();
}
}
http://www.dotnettutorials.com/tutorials/database/upload-files-sql-database-cs.aspx
Related
This question already has answers here:
How to store c# imagesource into database ?
(2 answers)
Storing images in SQL Server?
(8 answers)
Convert memory stream to BitmapImage?
(2 answers)
Closed 10 months ago.
I would like to insert image to my database. After clicking button the image should be retrieved from database and showed. How to do it?
Thats what I am sending to database:
//Send my img
private void SendImageMessageClicked(object sender, MouseButtonEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Images PNG (.png)|*.png";
if (openFileDialog.ShowDialog() == true)
{
string message = imageToByteArray(System.Drawing.Image.FromFile(openFileDialog.FileName)).ToString();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
con.Open();
cmd.CommandText = "INSERT INTO messages VALUES(null, " + userId + ", " + secondUserId + ", '" + message + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
writeMessage.Text = "";
con.Close();
}
}
// convert image to byte array
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
That is how I am trying to get it back:
while (dr.Read())
{
BitmapImage image = new BitmapImage();
MemoryStream stream;
stream = new MemoryStream(Encoding.ASCII.GetBytes((string)dr[3]));
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
imgMsg.Source = image;
}
this is example code, how to INSERT image (u should use VARBINARY(MAX) type in column):
Image image = Image.FromFile(#"D:\test\pictures\react-redux.png");
byte[] imageAsByteArr = ImageToByteArray(image);
using (SqlCommand command = new SqlCommand("insert into ImageTable values(2,#binaryValue)", conn))
{
command.Parameters.Add("#binaryValue", SqlDbType.VarBinary, imageAsByteArr.Length).Value = imageAsByteArr;
command.ExecuteNonQuery();
}
code above is using ImageToByteArray(...):
https://stackoverflow.com/a/3801289/12262729
when it comes to retrieve this data, let read this answer:
https://stackoverflow.com/a/7724595/12262729
after u retrieved data, let convert it to image:
https://stackoverflow.com/a/27774058/12262729
I am using C# Windows application for trying to download 700 MB to 2GB video file from SQL server using C# windows application. before this I have error (Connection time out) during upload file I have resolved that with extend connection time with 30 seconds on SSMS.
Now I get this message:
The code I'm using:
private void OpenFile(string id)
{
using (SqlConnection cn = GetConnection())
{
string query = "select * from CHATVIDEO where ID=#id";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.Add("#id", SqlDbType.NVarChar).Value = id;
cn.Open();
var reader = cmd.ExecuteReader();
if (reader.Read())
{
var name = reader["VDONAME"].ToString();
var data = (byte[])reader["PATHLINK"];
var extn = reader["Extension"].ToString();
var dtimes = reader["SentDateTime"].ToString();
var newfile = path + name.Replace(extn, id + dtimes) + extn;
File.WriteAllBytes(newfile, data);
//System.Diagnostics.Process.Start(newfile);
newerfile = newfile.ToString();
}
cn.Close();
}
}
This question already has answers here:
Insert 2 million rows into SQL Server quickly
(8 answers)
Closed 2 years ago.
I want to create 900.000 new rows in a database and in each of these rows the entry from the array should be written into the column Products.
My solution mentioned below works but it takes over an hour. How can this be done faster?
My very slow solution:
for (int i = 1; i <= 900000; i++)
{
string SQL_command = "INSERT INTO Database(Produkte) VALUES(" + ProductArray[i] + ")";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(SQL_command , con);
cmd.ExecuteNonQuery();
con.Close();
}
I use SQL Server and C#
Instead of opening and closing your connection with each call, open the connection once, then run all the INSERT statements, then close the connection:
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
for (i = 1; i <= 900000; i++) {
string SQL_command = "INSERT INTO Database(Produkte) VALUES(" + ProductArray[i] + ")";
using (SqlCommand cmd = new SqlCommand(SQL_command , con))
{
cmd.ExecuteNonQuery();
}
}
}
I want to create mysql database backup using c#. But this code do some problem because in my database i used "latin1_swedish_ci" thats why after export localize data convert into this form "مرسلی".
try
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (MySqlConnection conn = new MySqlConnection(con))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ExportToFile(path + "\\backup.sql");
conn.Close();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I'm trying to connect to a SQL Server on a local machine, run a SQL command against it and log the results. The code keeps failing at making the connection to the server.
I can't quite see what I'm doing wrong. Everything I've searched for either doesn't apply to this method or seems to match what I'm doing. I think I have other problems in the code as well, but I can't even get past the SQL connection to test the rest. Here is my code:
string svrConnection = "Server=.\\sqlexpress;Database="+db+";User ID=user;Password=password;";
SqlConnection con;
SqlCommand cmd;
Directory.CreateDirectory("C:\\"db"\\");
FileInfo file = new FileInfo("C:\\script.sql");
string PCS = file.OpenText().ReadToEnd();
con = new SqlConnection(svrConnection);
StreamWriter PCSLog = new StreamWriter(#"C:\\" + db + "\\Log" + db + ".txt");
try
{
con.Open();
cmd = new SqlCommand(PCS, con);
cmd.ExecuteNonQuery();
using (SqlDataReader pcsrdr = cmd.ExecuteReader())
using (PCSLog)
{
while (pcsrdr.Read())
PCSLog.WriteLine(pcsrdr[0].ToString() + pcsrdr[1].ToString() + ",");
}
PCSLog.Close();
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection !", ex.Message);
}
There are additional problems with your code:
The Lines
cmd.Dispose();
con.Close();
are not guaranteed to execute if an exception occurs.
You call PCSLog.Close AFTER after you have disposed of it
I would suggest this as a better alternative (irrespective of the other comments made here).
string svrConnection = "Server=.\\sqlexpress;Database="+db+";User ID=user;Password=password;";
Directory.CreateDirectory("C:\\" + db + "\\");
FileInfo file = new FileInfo("C:\\script.sql");
string PCS = file.OpenText().ReadToEnd();
try
{
using (SqlConnection con = new SqlConnection(svrConnection))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(PCS, con))
{
cmd.ExecuteNonQuery();
using (SqlDataReader pcsrdr = cmd.ExecuteReader())
using (StreamWriter PCSLog = new StreamWriter("C:\\" + db + "\\Log" + db + ".txt"))
{
while (pcsrdr.Read())
PCSLog.WriteLine(pcsrdr[0].ToString() + pcsrdr[1].ToString() + ",");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection !", ex.Message);
}
I think the issue is your connection string. Try this:
string svrConnection = "Data Source=.\\SQLEXPRESS;Initial Catalog=" + db + ";User Id=user;Password=password;"
Or to get a connection using your windows credentials:
string svrConnection = "Data Source=.\\SQLEXPRESS;Initial Catalog=" + db + ";Trusted_Connection=True;"
Also, ExecuteNonQuery does not run each command separated by GO. You will need to split your query into sections and run each individually.