您的位置:首页 > 数据库

C# 读取写入数据到ACCESS数据库基于FRAMEWORK2.0

2017-02-16 18:22 561 查看
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;

public partial class unsubscribe : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string guid = Request.QueryString["guid"];
string email = Request.QueryString["email"];
if(guid!=null&&guid!=""&&email!=null&&email!=""){

string filePath = ConfigurationManager.AppSettings["filePath"].ToString();
bool res = checkData(filePath, guid, email);
if(!res){//如果不存在则写入
saveData(filePath, guid, email);
lblresult.Text = "退订成功!";
}
else
{
lblresult.Text = "请不要重复提交!";
}

}
else
{
lblresult.Text = "无效的参数!";
}

}

static void Main(string[] args)
{

}

/// <summary>
/// 获取ACCESS文件,写数据到.mdb
/// </summary>
/// <returns></returns>
public static OleDbConnection getConn(String filePath)
{
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source="+filePath;
OleDbConnection tempconn = new OleDbConnection(connstr);
return tempconn;
}

/// <summary>
/// 去重复数据
/// </summary>
/// <param name="filePath"></param>
/// <param name="guid"></param>
/// <param name="email"></param>
/// <returns></returns>
public static bool checkData(string filePath, string guid, string email)
{

bool res = false; //定义返回值,并设置初值

try
{
OleDbConnection conn = getConn(filePath); //getConn():得到连接对象
conn.Open();
string sql = "select * from unsubscribe  where EUD_GUID='" + guid + "' and EUD_EMAIL = '" + email+"'";
OleDbCommand myCommand = new OleDbCommand(sql, conn);
OleDbDataReader reader = myCommand.ExecuteReader(); //执行command并得到相应的DataReader
//下面把得到的值
if (reader!=null&&reader.Read())
{
if (!reader["id"].ToString().Equals(""))
res = true;
}
else //如没有该记录,则返回false!
{
res = false;
}
reader.Close();
conn.Close();
}
catch (Exception e)
{
throw(new Exception("数据库出错:" + e.Message)) ;
}

return res;
}

/// <summary>
/// 写入数据到ACCESS中
/// </summary>
/// <returns></returns>
public static bool saveData(string filePath, string guid, string email)
{

bool tempvalue = false; //定义返回值,并设置初值
//下面把note中的数据添加到数据库中!
try
{

OleDbConnection conn = getConn(filePath); //getConn():得到连接对象
conn.Open();

//设置SQL语句
String sql = "INSERT INTO unsubscribe(EUD_GUID,EUD_EMAIL,EUD_CREATE_DATE)";
sql += " VALUES(";
sql += "'" + guid+ "',";
sql += "'" + email + "',";
sql += "now()";
sql += ")";

OleDbCommand insertcmd = new OleDbCommand(sql, conn);
insertcmd.ExecuteNonQuery();

conn.Close();
tempvalue = true;
}
catch (Exception e)
{
throw (new Exception("数据库出错:" + e.Message));
}
return tempvalue;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐