解决方案 »
- 错误 CS0115: “OpenGL_3D.Service1.Dispose(bool)”: 没有找到适合的方法来重写
- WINFORM 读取指定目录里的图片到pictruebox的问题??!!
- 可以用struct来写一个链表吗?
- 在DataGridView列中加入非本表数据的图片
- 语法问题:关于for循环中使用break语句,请高手指教一下,谢谢
- 从DataGrid中选出部分行数据进行排序的问题
- 请教ODBC操作EXCEL的小问题。
- 在十个Button中我想判断那个Buttont.ID=aaa怎么写呀
- 后台生成的文本文件如何输到客户端下载.
- 索引超出数组界限,求助!!
- WINFORM 遇到问题需要关闭
- C# panel中如何显示文本
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows 窗体设计器生成的代码 /// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.button1 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.label1 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.label2 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(196, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "打开";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk);
//
// label1
//
this.label1.Location = new System.Drawing.Point(13, 58);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(258, 55);
this.label1.TabIndex = 1;
//
// button2
//
this.button2.Enabled = false;
this.button2.Location = new System.Drawing.Point(196, 166);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "生成";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// saveFileDialog1
//
this.saveFileDialog1.FileName = "LinqToAccess_YDH.cs";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(13, 142);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(149, 12);
this.label2.TabIndex = 3;
this.label2.Text = "密码(如果没有密码则为空)";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(15, 168);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 21);
this.textBox1.TabIndex = 4;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 211);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label2);
this.Controls.Add(this.button2);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.ResumeLayout(false);
this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox1;
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;/************************************************************************************
* 作者 袁东辉 时间:2011-6
* Email [email protected] [email protected]
* 作用 Linq to Access 自动生成实体类和执行类
* VS版本 2010
***********************************************************************************/namespace myLinqtoAccess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} /// <summary>
/// 打开按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
this.openFileDialog1.ShowDialog();
} /// <summary>
/// 点击文件打开
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
this.label1.Text = this.openFileDialog1.FileName;
this.button2.Enabled = true;
} /// <summary>
/// 生成按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
#region 头--拼接生成文件的头
string myclass =
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.OleDb;
using System.Data;namespace YDHnamespace
{
#region 内部使用 /// <summary>
/// 状态
/// </summary>
enum Status_y
{
/// <summary>
/// 表示新增
/// </summary>
new_y = 0,
/// <summary>
/// 表示初始化后
/// </summary>
initialized_y=1,
/// <summary>
/// 表示被修改
/// </summary>
update_y=2, /// <summary>
/// 表示被删除
/// </summary>
delete_y=3
} /// <summary>
/// 表的基类
/// </summary>
class ydhTable
{
/// <summary>
/// 内部使用,不要修改。
/// </summary>
internal Status_y MyStatus { get; set; }
//不是非常清楚泛型的概念,研究了半天,貌似这里不能用知道的大侠告诉我
public SortedList<string, object> Changes = null; /// <summary>
/// 初始化的时候为新的
/// </summary>
public ydhTable()
{
this.MyStatus = Status_y.new_y;
} /// <summary>
/// 内部使用
/// </summary>
/// <param name=""name"">列名</param>
/// <param name=""value"">列值</param>
protected void SetChange(string name, object value)
{
if (this.Changes == null)
{
this.Changes = new SortedList<string, object>();
}
if (this.Changes.IndexOfKey(name) != -1)
{
this.Changes[name] = value;
}
else
{
this.Changes.Add(name, value);
}
} /// <summary>
/// 主键
/// </summary>
List<string> _Pkey = null; /// <summary>
/// 主键
/// </summary>
public List<string> Pkey
{
get
{
if (this._Pkey == null)
{
this._Pkey = new List<string>();
}
return _Pkey;
}
set { _Pkey = value; }
}
} #endregion #region 表";
string ydhAcessEntity_string = @"
/// <summary>
/// 主类型,里面有新增,删除,修改的方法
/// </summary>
class ydhAcessEntity
{
";
string ydhAcessEntity_ydhAcessEntity = @" public ydhAcessEntity()
{
try
{
using (OleDbConnection conn = new OleDbConnection(mycon))
{
OleDbCommand comm = new OleDbCommand();
comm.Connection = conn;
OleDbDataAdapter oa = new OleDbDataAdapter(comm);
DataTable dt = new DataTable();
";
string ydhAcessEntity_Insert_y = null;
string ydhAcessEntity_Submit_y = null; #endregion //Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\bin\Debug\a07.accdb;Jet OLEDB:Database Password=123
string dbpath = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Jet OLEDB:Database Password={1}",this.label1.Text,this.textBox1.Text);
try
{
using (OleDbConnection Myconn = new OleDbConnection(dbpath))
{
Myconn.Open(); DataTable SchemaTalbe = Myconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataTable keys = Myconn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, null);
//Access数据库的路径
ydhAcessEntity_string += " string mycon = @\"" + dbpath + "\";" + "\r\n";
//文件拼接。
ydhAcessEntity_ydhAcessEntity += E_mainF1(SchemaTalbe, Myconn, keys);
ydhAcessEntity_Insert_y += E_mainF2(SchemaTalbe, Myconn);
ydhAcessEntity_Submit_y += E_mainF3(SchemaTalbe, Myconn, keys); #region 开始考虑的太少,把太多函数写在一个for循环里面了 for (int i = 0; i < SchemaTalbe.Rows.Count; i++)
{
string namey = Convert.ToString(SchemaTalbe.Rows[i]["Table_Name"]); string mytable = E_table1(namey);
ydhAcessEntity_string += E_main1(namey);
//ydhAcessEntity_ydhAcessEntity+= DataTable ColNames = Myconn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, SchemaTalbe.Rows[i]["Table_Name"].ToString(), null }); for (int j = 0; j < ColNames.Rows.Count; j++)
{
string col = E_table2(Convert.ToInt32(ColNames.Rows[j]["data_type"]), Convert.ToString(ColNames.Rows[j]["column_name"]));
mytable += col;
} #endregion
mytable += @"
}";
myclass += mytable;
} //生成文件的最后拼接。
myclass += @" #endregion
";
ydhAcessEntity_string += ydhAcessEntity_ydhAcessEntity;
ydhAcessEntity_string += ydhAcessEntity_Insert_y;
ydhAcessEntity_string += ydhAcessEntity_Submit_y;
ydhAcessEntity_string += @"
}";
myclass += ydhAcessEntity_string; myclass +=@"
}";
}
}
catch (Exception me)
{
MessageBox.Show("数据库打开失败:原因" + me.Message);
return;
} #region 生成cs文件 this.saveFileDialog1.ShowDialog();
string FileName = this.saveFileDialog1.FileName;
using (StreamWriter objWriter = new StreamWriter(FileName, false, System.Text.Encoding.Default))
{
objWriter.WriteLine(myclass);
}
MessageBox.Show("生成成功!"); #endregion
}
#region 集中处理字符串
SortedList<int, string> _duiying = null;
/// <summary>
/// 由于取出来得类型都是用数字表示的,所以在这里加个对应。
/// </summary>
/// <returns></returns>
SortedList<int, string> Getduying()
{
if (this._duiying == null)
{
this._duiying = new SortedList<int, string>();
_duiying.Add(11, "bool");
_duiying.Add(7, "DateTime");
_duiying.Add(3, "int");
_duiying.Add(6, "decimal");
_duiying.Add(130, "string");
}
return this._duiying;
} //以下都是用于拼接的类
//处理“表的类”1
string E_table1(string name)
{
string mytable = " class " + name + @" : ydhTable
{
";
return mytable;
} string E_table2(int datatype,string columnname)
{
SortedList<int, string> dy=Getduying();
string mytype = dy[datatype];
if (mytype != "string")
{
mytype = mytype + "?";
}
string col = @"
" + mytype + " _" + columnname + @" = null; public " + mytype + " " + columnname + @"
{
get { return _" + columnname + @"; }
set
{
if (this.MyStatus == Status_y.initialized_y)
{
this.MyStatus = Status_y.update_y;
this.SetChange(""" + columnname + @""", value);
}
if (this.MyStatus == Status_y.update_y)
{
this.SetChange(""" + columnname + @""", value);
}
_" + columnname + @" = value;
}
}";
//string col = " public " + dy[datatype] + " " + columnname + @" { get; set; }
//";
return col;
} //处理主类的类
string E_main1(string name)
{
string str = @" /// <summary>
/// 如果想新增和删除,请用方法,不要用自带的add和remove
/// </summary>
public List<" + name + "> " + name + @" { get; set; }
";
return str;
} string E_mainF1(DataTable xunhuan1, OleDbConnection Myconn,DataTable PK)
{
string str = "";
for (int i = 0; i < xunhuan1.Rows.Count; i++)
{
string name = Convert.ToString(xunhuan1.Rows[i]["Table_Name"]);
str += @"
this." + name + @" = new List<YDHnamespace." + name + @">();
comm.CommandText = ""select * from " + name + @""";
dt.Clear();
oa.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
YDHnamespace." + name + @" mydd = new " + name + @"();
";
//判断主键部分
DataRow[] mdr = PK.Select("TABLE_NAME='" + name + "'");
if (mdr.Length > 0)
{ foreach (var item in mdr)
{
str += @"
mydd.Pkey.Add(""" + Convert.ToString(item["COLUMN_NAME"]) + "\");";
}
}
DataTable ColNames = Myconn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, xunhuan1.Rows[i]["Table_Name"].ToString(), null });
for (int j = 0; j < ColNames.Rows.Count; j++)
{
string col = Convert.ToString(ColNames.Rows[j]["column_name"]);
string strr1 = @"
if (dt.Rows[i][""" + col + @"""] != DBNull.Value)
{
mydd." + col + " = Convert." + getConvert(Convert.ToInt32(ColNames.Rows[j]["data_type"])) + "(dt.Rows[i][\"" + col + @"""]);
}";
//mydd." + col + " = Convert." + getConvert(Convert.ToInt32(ColNames.Rows[j]["data_type"])) + "(dt.Rows[i][\"" + col + "\"]);";
str = str + strr1;
}
string str2 = @"
mydd.MyStatus = Status_y.initialized_y;
this." + name + @".Add(mydd);
}
";
str = str + str2;
}
return str + @"
}
}
catch (Exception me)
{
throw new Exception(""ydhAcessEntity初始化错误! "" + me.Message);
}
}";
} string getConvert(int type)
{
SortedList<int, string> mduiying = Getduying();
string con1 = mduiying[type];
string con2 = null;
switch (con1)
{
case "bool":
con2 = "ToBoolean";
break;
case "DateTime":
con2 = "ToDateTime";
break;
case "int":
con2 = "ToInt32";
break;
case "decimal":
con2 = "ToDecimal";
break;
case "string":
con2 = "ToString";
break;
}
return con2;
} string E_mainF2(DataTable xunhuan1, OleDbConnection Myconn)
{
string strre = "";
for (int i = 0; i < xunhuan1.Rows.Count; i++)
{
string name = Convert.ToString(xunhuan1.Rows[i]["Table_Name"]);
strre += @"
/// <summary>
/// 注意,只有在Submit_y函数执行之后,才会在数据库里新增,现在只是在类里新增了。
/// </summary>
/// <param name=""instance""></param>
public void Insert_y(" + name + @" instance)
{
if (instance.MyStatus == Status_y.new_y)
{
this." + name + @".Add(instance);
}
else
{
throw new Exception(""此实例并不是新的实例,不能添加!"");
}
} /// <summary>
/// 注意,只有在Submit_y函数执行之后,才会真正删除,现在只是标记
/// </summary>
/// <param name=""instance""></param>
public void Delete_y(" + name + @" instance)
{
instance.MyStatus = Status_y.delete_y;
}
";
}
return strre;
}
string E_mainF3(DataTable xunhuan1, OleDbConnection Myconn, DataTable PK)
{
string strre = @"
/// <summary>
/// 提交修改
/// </summary>
/// <returns></returns>
public void Submit_y()
{
string sql = """";";
for (int i = 0; i < xunhuan1.Rows.Count; i++)
{
string name = Convert.ToString(xunhuan1.Rows[i]["Table_Name"]);
DataTable ColNames = Myconn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, name, null });
string mpk = "";
DataRow[] mdr = PK.Select("TABLE_NAME='" + name + "'");
if (mdr.Length > 0)
{ foreach (var item in mdr)
{
DataRow[] pktype = ColNames.Select("COLUMN_NAME='" + Convert.ToString(item["COLUMN_NAME"]) + "'");
mpk += " \"" + Convert.ToString(item["COLUMN_NAME"]) + "=\" + " + this.GetConvert2(Convert.ToInt32(pktype[0]["data_type"]), "item." + Convert.ToString(item["COLUMN_NAME"])) + " + \",\"";//'\" + item." + Convert.ToString(item["COLUMN_NAME"]) + " + \"',\"";
}
}
if (mpk != "")
{
mpk = mpk.Substring(0, mpk.Length - 2) + "\"";
}
string shou = @"
foreach (var item in this." + name + @")
{
string pk = null;
if (item.Pkey == null)
{
throw new Exception(""" + name + @"表没有主键,不能做提交!"");
}
else
{
pk = " + mpk + @" + "";"";
} SortedList<string, object> panduan = new SortedList<string, object>();";
string ins1 = @"
switch (item.MyStatus)
{
case Status_y.delete_y:
sql += ""delete from " + name + @" where "" + pk;
break;
case Status_y.new_y:
sql += CreatInsertSql(panduan,""" + name + @""");
break;
case Status_y.update_y :
sql += CreatUpdateSql(item.Changes, """ + name + @""") + "" where "" + pk;
break;
";
string ins2 = "";
//string insert1 = "";
//string insert2 = "";
for (int j = 0; j < ColNames.Rows.Count; j++)
{
ins2 += @"
panduan.Add(""" + Convert.ToString(ColNames.Rows[j]["COLUMN_NAME"]) + "\",item." + Convert.ToString(ColNames.Rows[j]["COLUMN_NAME"]) + ");";
//insert1 += Convert.ToString(ColNames.Rows[j]["COLUMN_NAME"]) + ",";
//insert2 += this.GetConvert2(Convert.ToInt32(ColNames.Rows[j]["data_type"]), "item." + Convert.ToString(ColNames.Rows[j]["COLUMN_NAME"])) + " + \",\" + "; }
//insert1 = insert1.Substring(0, insert1.Length - 1);
//insert2 = insert2.Substring(0, insert2.Length - 9);
// string xiao1 = @"
// case Status_y.new_y:
// sql += ""insert into " + name + @" (" + insert1 + ")values(\" + " + insert2 + @" + "");"";
// break;"; //case Status_y.update_y :
// sql += ""update " + name + @" set "";
// break;
string dawei = @"
}
}";
strre += shou + ins2 + ins1 + dawei;
} string send= @"
try
{
using (OleDbConnection conn = new OleDbConnection(mycon))
{
OleDbCommand comm = new OleDbCommand(sql, conn);
comm.Connection.Open();
string[] sqls = sql.Split(';');
foreach (var item in sqls)
{
if (item != """")
{
comm.CommandText = item;
comm.ExecuteNonQuery();
}
}
comm.Connection.Close();
}
}
catch(Exception me)
{
throw new Exception(""Execute Sql Wrong!"" + me.Message);
}
}
/// <summary>
/// 生成insert语句
/// </summary>
/// <param name=""shuru""></param>
/// <returns></returns>
string CreatInsertSql(SortedList<string, object> lie,string tableName)
{
string sql = ""insert into "" + tableName + "" ("";
string sql2 = "")values("";
string sql3 = "");"";
string sqlA = """";
string sqlB = """";
foreach (var item in lie)
{
if (item.Value != null)
{
sqlA = item.Key + "","";
sqlB = GetConvert2(item.Value, item.Value.ToString()) + "","";
}
}
if (sqlA != """")
{
sqlA = sqlA.Substring(0, sqlA.Length - 1);
sqlB = sqlB.Substring(0, sqlB.Length - 1);
}
return sql + sqlA + sql2 + sqlB + sql3;
} /// <summary>
/// 生成update语句
/// </summary>
/// <param name=""Changes""></param>
/// <param name=""tableName""></param>
/// <returns></returns>
string CreatUpdateSql(SortedList<string, object> Changes, string tableName)
{
string sql = ""update "" + tableName + "" set "";
string sql2 = """";
foreach (var item in Changes)
{
sql2 += item.Key + ""="" + GetConvert2(item.Value, Convert.ToString(item.Value)) + "","";
}
if (sql2 != """")
{
sql2 = sql2.Substring(0, sql2.Length - 1);
} return sql + sql2;
} /// <summary>
/// 根据类型生成合适的SQL部分
/// </summary>
/// <param name=""datatype""></param>
/// <param name=""value""></param>
/// <returns></returns>
string GetConvert2(object datatype, string value)
{
switch (datatype.GetType().ToString())
{
case ""System.Int32"":
case ""System.Decimal"":
case ""System.Boolean"":
return value;
case ""System.String"":
return ""'"" + value + ""'"";
case ""System.DateTime"":
return ""#"" + value + ""#"";
}
throw new Exception(""SQLstring Wrong!!!"");
}"; return strre + send;
} /// <summary>
/// 改了方法之后应该是用不到了
/// </summary>
/// <param name="datatype"></param>
/// <param name="value"></param>
/// <returns></returns>
string GetConvert2(int datatype,string value)
{
switch (this._duiying[datatype])
{
case "int":
case "decimal":
case "bool":
return value;
case "string":
return "\"'\" + " + value + " + \"'\"";
case "DateTime":
return "\"#\" + " + value + " + \"#\"";
}
return "SQLstring Wrong!!!";
} #endregion
}
}
可以把数据存进DataSet,
再用LINQ to DataSet啊
怎么弄??
我完全是仿照Linq2Sql做的啊,你是不是觉得linq2sql也没优势啊?
博客上写的比这里清楚,想拷贝代码的去博客吧。
在拼insert的sql时,需要把每个value的特殊字符(如单引号“'”要double一下)加以处理,否则语法出错
你的意思是说可以用linq 访问你的库,
你的库再去访问数据库?可以这么理解么?