我只是尝试创建并写入数据库文件。
我不知道为什么连接字符串变成了这样:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
使用此连接字符串,我收到此错误:
错误CS1009无法识别的转义序列
XXX_DATABASE_TEST D:\ FOLDER \ XXX_DATABASE_TEST \ Form1.cs
所以我把“/”更改为“\”:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:/Users/User/Documents/DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
错误已经消失,表单加载,但数据库为空,不写入。你能帮我解决一下,我在这里做错了什么:
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.Sql;
using System.Data.SqlClient;
namespace XXX_DATABASE_TEST
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
cmd = new SqlCommand("INSERT INTO testdata VALUES (Name, IDo, Gender) VALUES (@Name,@IDo,@Gender)", con);
cmd.Parameters.Add("@Name", textBox1.Text);
cmd.Parameters.Add("@IDo", textBox1.Text);
cmd.Parameters.Add("@Gender", comboBox1.SelectedItem.ToString());
cmd.ExecuteNonQuery();
}
}
}