想我已經從一類這種方法:使用C#中的UPDATE mysql命令
private void btnChangeImage_Click(object sender, EventArgs e)
{
using (var openFileDialogForImgUser = new OpenFileDialog())
{
string location = null;
string fileName = null;
openFileDialogForImgUser.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp|All Files (*.*)|*.*"; // filtering only picture file types
var openFileResult = openFileDialogForImgUser.ShowDialog(); // show the file open dialog box
if (openFileResult == DialogResult.OK)
{
using (var formSaveImg = new FormSave())
{
var saveResult = formSaveImg.ShowDialog();
if (saveResult == DialogResult.Yes)
{
imgUser.Image = new Bitmap(openFileDialogForImgUser.FileName); //showing the image opened in the picturebox
location = openFileDialogForImgUser.FileName;
fileName = openFileDialogForImgUser.SafeFileName;
FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read); //Creating a filestream to open the image file
int fileLength = (int)fs.Length; // getting the length of the file in bytes
byte[] rawdata = new byte[fileLength]; // creating an array to store the image as bytes
fs.Read(rawdata, 0, (int)fileLength); // using the filestream and converting the image to bits and storing it in an array
MySQLOperations MySQLOperationsObj = new MySQLOperations("localhost", "root", "myPass");
MySQLOperationsObj.saveImage(rawdata);
fs.Close();
}
else
openFileDialogForImgUser.Dispose();
}
}
}
}
而且從另一類這個方法(MySQLOperations):
public void saveImage(byte[] rawdata)
{
try
{
string myConnectionString = "Data Source = " + server + "; User = " + user + "; Port = 3306; Password = " + password + ";";
MySqlConnection myConnection = new MySqlConnection(myConnectionString);
string currentUser = FormLogin.userID;
string useDataBaseCommand = "USE " + dbName + ";";
string updateTableCommand = "UPDATE tblUsers SET UserImage = @file WHERE Username = \'" + currentUser + "\';";
MySqlCommand myCommand = new MySqlCommand(useDataBaseCommand + updateTableCommand, myConnection);
myCommand.Parameters.AddWithValue("@file", rawdata);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
如果非要我,這是我的MySQLOperations類的構造函數:
public MySQLOperations(string server, string user, string password)
{
this.server = server;
this.user = user;
this.password = password;
}
我想要做的是保存圖像文件(用戶選擇t通過打開的文件對話框)到數據庫。問題是我得到這個錯誤:「你的SQL語法有錯誤;查看與你的MySQL服務器版本相對應的手冊,以便在正確的語法附近使用'; UPDATE tblUsers SET UserImage = _binary'?PNG ...(和因此,我無法真正將該文件保存在數據庫中,我很想張貼關於如何在MessageBox中看到錯誤的圖片,但我想我的帳戶沒有被賦予特權
我不太確定語法錯誤在哪裏,我在想,它在@file中 - 但這只是一個猜測,你的幫助將非常感謝。 ,表列UserImage有一個LONGBLOB類型。
我也有興趣知道的其他東西:
- 是否有必要,我將另一列添加我的表來存儲 大小的文件(因爲我會需要檢索文件 後來上顯示圖像)?
- 是否可以使用方法中的using語句 btnChangeImage_Click?
非常感謝。
編輯:得到解決的問題。這種簡單的事情沒有給予重視。感謝所有試圖提供幫助的人。我仍然願意聽到你對底部問題(有關子彈的問題)的意見。
爲什麼你不像'@ file'那樣參數化你的'username'值? –
是的,是的。好點子。我申請了,但似乎沒有解決問題。 – Jill
你確定dbName有一個值嗎?否則你的陳述是:USE; UPDATE ... – Loathing