using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace shoujihao { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Imports_Click(object sender, EventArgs e) { //文件打开对话框 OpenFileDialog dlg = new OpenFileDialog(); //如果用户没选择文件,就返回 if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } //获得用户选择的文件 string fileName = dlg.FileName; //读取所选择的文件 using(Stream fs = new FileStream(fileName,FileMode.Open)) using (StreamReader reader = new StreamReader(fs, Encoding.Default)) { //开始读取这个文件 string line; //跳过第一行 line = reader.ReadLine(); //创建数据库链接 using (MySqlConnection conn = MySqlHelper.CreateConnection()) //事务回滚 using(MySqlTransaction tx = conn.BeginTransaction()) { try { while ((line = reader.ReadLine()) != null) { //如果最后一行为空字符串,则跳出整个循环 if (string.IsNullOrEmpty(line)) { break; } //把line字符串按照,号进行分割 string[] lines = line.Split(‘,‘); //去掉字符串中的“”号 string MobileNumber = lines[1].Trim(‘"‘); string MobileArea = lines[2].Trim(‘"‘); string MobileType = lines[3].Trim(‘"‘); //插入数据库 //MySqlHelper.ExecuteNonQuery(conn, "insert into t_mobile(MobileNumber,MobileArea,MobileType) values(@MobileNumber,@MobileArea,@MobileType))", // new MySqlParameter { ParameterName = "@MobileNumber", Value = MobileNumber }, // new MySqlParameter { ParameterName = ",@MobileArea", Value = MobileArea }, // new MySqlParameter { ParameterName = "@MobileType", Value = MobileType }); MySqlHelper.ExecuteNonQuery(conn, "INSERT INTO t_mobile(MobileNumber,MobileArea,MobileType) VALUES(@MobileNumber,@MobileArea,@MobileType)", new MySqlParameter { ParameterName = "@MobileNumber", Value = MobileNumber }, new MySqlParameter { ParameterName = "@MobileArea", Value = MobileArea }, new MySqlParameter { ParameterName = "@MobileType", Value = MobileType }); } tx.Commit(); } catch(Exception ex) { tx.Rollback(); MessageBox.Show("导入失败" + ex.Message); } } } MessageBox.Show("导入成功!"); } private void cx_Click(object sender, EventArgs e) { //获得用户输入的手机号码 string phoneNum = textPhoneNum.Text; //取用户手机号前七位 string phoneFix = phoneNum.Substring(0, 7); //去数据库查询信息 DataTable table = MySqlHelper.ExecuteQuery("SELECT MobileNumber,MobileArea FROM t_mobile WHERE MobileNumber = @phoneFix", new MySqlParameter { ParameterName = "@phoneFix", Value = phoneFix }); // if (table.Rows.Count <= 0) { MessageBox.Show("木有查询到数据"); } else { DataRow row = table.Rows[0]; string MobileArea = (string)row[1]; string MobileType = (string)row[2]; MessageBox.Show(MobileArea+MobileType); } } } }
时间: 2024-10-06 09:22:30