我正在使用 WPF (C#) 编写音乐播放器应用程序。作为其功能的一部分,我正在填充一个音乐库,在其中存储 mp3 文件的标题和路径。用户可以为其音乐库选择一个根文件夹,然后内容将填充到“歌曲”表中。这是我编写的代码:
private void Populate_Click(object sender, RoutedEventArgs e)
{
// Folder browser
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.ShowDialog();
string DirectoryPath = System.IO.Path.GetDirectoryName(dlg.SelectedPath);
// Get the data directory
string[] A = Directory.GetFiles(DirectoryPath, "*.mp3", SearchOption.AllDirectories);
string[] fName = new string[A.Count()];
// Initialize connection
string connstr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
// Create the SqlCommand
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertSongs";
// Create the parameters and execute the command
for (int i = 0; i < A.Count(); i++)
{
fName[i] = System.IO.Path.GetFileName(A[i]);
cmd.Parameters.AddWithValue("@Title", fName[i]);
cmd.Parameters.AddWithValue("@Path", A[i]);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error: " + ex.Message);
}
finally
{
listBox1.Items.Add(A[i]);
listBox2.Items.Add(fName[i]);
cmd.Parameters.Clear();
}
}
// Close the connection
cmd.Dispose();
conn.Close();
conn.Dispose();
}
存储过程的代码很简单 -
ALTER PROCEDURE dbo.InsertSongs
(
@Title nvarchar(50),
@Path nvarchar(50)
)
AS
INSERT INTO Songs(Title, Path) VALUES(@Title, @Path)
现在,当我执行该程序时,没有抛出任何错误消息(文件名和目录名的大小小于 50)。但是,在执行结束时,Songs 表中没有插入任何值。
歌曲表描述如下:
ID int Title nvarchar(50) Path nvarchar(50)
我不确定我哪里出错了:我也尝试过使用SqlParameter,然后将参数类型定义为大小为50的NVARCHAR,但无济于事。我可以请你在这里帮助我吗?非常感谢。
最佳答案
整个用户实例和AttachDbFileName=
方法是有缺陷的 - 充其量! Visual Studio 将复制 .mdf
文件,并且很可能,您的 INSERT
工作得很好 - 但您只是查看 <强>错误的.mdf文件最终!
如果您想坚持使用此方法,请尝试在 myConnection.Close()
调用上放置断点 - 然后使用 SQL Server 检查 .mdf
文件Mgmt Studio Express - 我几乎可以肯定您的数据就在那里。
我认为真正的解决方案是
安装 SQL Server Express(而且您已经完成了)
安装 SQL Server Management Studio Express
在SSMS Express中创建数据库,并为其指定一个逻辑名称(例如
SongsDatabase
)使用其逻辑数据库名称(在服务器上创建它时给出)连接到它 - 并且不要弄乱物理数据库文件和用户实例。在这种情况下,您的连接字符串将类似于:
Data Source=.\\SQLEXPRESS;Database=SongsDatabase;Integrated Security=True
其他一切都与以前完全相同相同...
关于c# - 存储过程 - INSERT 查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12728610/