想我已经从一类这种方法:使用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