(一)配置文件
1.添加一个配置文件
2.在配置文件中的connectionStrings中add一个connectionString
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnStr" connectionString="Data Source=VVP-PC\JADAM;Initial Catalog=master;Integrated Security=true"/>
</connectionStrings>
</configuration>
3.在项目中添加引用system.configuration,然后using system.configuration;
4.在实例化SqlConnection对象中使用配置文件中的连接字符串
using (SqlConnection conn = new SqlConnetion(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
(二)导入数据
private void btnImport_Click(object sender, EventArgs e)
{
//打开文件夹对话框
FolderBrowserDialog dlg = new FolderBrowserDialog();
//如果用户没有选择文件夹,则跳出当前函数
if (dlg.ShowDialog() != DialogResult.OK)
{
return;
}
//导入数据前先清空表中的内容
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "DELETE FROM T_Numbers";
cmd.ExecuteNonQuery();
}
}
//得到用户选择的文件夹路径
string path = dlg.SelectedPath;
//取文件夹下的所有TXT文件的文件名(包括所选文件夹下的子文件夹)
string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
//遍历每个文件
foreach (string file in files)
{
//读取文件名(无扩展名)
string 省运营商 = Path.GetFileNameWithoutExtension(file);
//使用ReadAllLines的重载方法,选择默认编码参数防止出现乱码
string[] lines = File.ReadAllLines(file, Encoding.Default);
//遍历每行数据
foreach (string line in lines)
{
string[] strs = line.Split('-');
string startNum = strs[0];
string endNum = strs[1];
string city = strs[2];
cmd.CommandText = "INSERT INTO T_Numbers (StartNum,EndNum,City) VALUES (@StartNum,@EndNum,@City)";
//每次循环先清除上次循环中添加的参数
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("StartNum", startNum));
cmd.Parameters.Add(new SqlParameter("EndNum", endNum));
cmd.Parameters.Add(new SqlParameter("City", 省运营商 + city));
cmd.ExecuteNonQuery();
}
}
}//End Using SqlCommand
}//End Using SqlConnection
MessageBox.Show("导入完成!");
}
看编码方式:在记事本点“另存为”后,可以看到编码方式
File.ReadAllLine()方法默认是UTF-8编码,可重载
(三)查询
private void btnSelect_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT City FROM T_Numbers WHERE @PhoneNum>=StartNum and @PhoneNum<=EndNum";
cmd.Parameters.Add("PhoneNum", txtPhoneNum.Text);
string result=Convert.ToString(cmd.ExecuteScalar());
MessageBox.Show("您所查询的号码"+txtPhoneNum.Text+"属于"+result);
}
}
当查询时输入一段错误的号码,在数据库中查询不到结果时,可以处理一下cmd.ExecuteScalar()返回值为null的情况。
(四)一段神奇代码
放在Main()方法最开始
string dataDir = AppDomain.CurrentDomain.BaseDirectory;
if (dataDir.EndsWith(@"\bin\Debug\")
|| dataDir.EndsWith(@"\bin\Release"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}
---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------