-
C#与VB.NET添加数据到Access数据库 - Dwaynerbing
一、VB.NET添加数据到Access数据库
1:VB.NET添加数据到Access数据库,其代码如下:
''' <summary>
''' 添加数据到数据库
''' </summary>
''' <param name="filepath">数据库文件的路径</param>
''' <returns>flase:添加失败;true:添加成功</returns>
''' <remarks></remarks>
Public Function DataInsert(ByVal filepath As String) As Boolean
Dim bolReturn As Boolean = False
Try
'连接数据库
Dim oleCon As OleDbConnection = getConnection(filepath)
'打开数据库
If (oleCon.State = ConnectionState.Open) Then oleCon.Close()
oleCon.Open()
'
Dim strCmd As String = "insert into Administrator (名字,性别,年龄) values (:名字,:性别,:年龄)"
Dim oleCmd As OleDbCommand = New OleDbCommand(strCmd, oleCon)
oleCmd.Parameters.AddWithValue("名字", "张三")
oleCmd.Parameters.AddWithValue("性别", "男")
oleCmd.Parameters.AddWithValue("年龄", "43")
oleCmd.ExecuteNonQuery()
oleCon.Close()
bolReturn = True
Catch ex As Exception
MessageBox.Show("添加失败", "提示")
End Try
Return bolReturn
Function
2:添加成功后的效果如下:
二、C#添加数据到Access数据库
1:C#添加数据到Access数据库,其代码如下:
/// <summary>
///添加数据到数据库
/// </summary>
/// <param name="intFlag">数据库标志位</param>
/// <param name="path">数据库文件</param>
/// <returns>true:添加成功</returns>
public bool DataInsert(int intFlag,string path )
{
bool bolReturn = false;
try
{
//连接数据库
OleDbConnection oleConn = getConnection(intFlag, path);
//打开数据
if (oleConn.State == ConnectionState.Open)
{
oleConn.Close();
}
oleConn.Open();
//执行语句
string strCmd = "insert into Administrator(名字,性别,年龄) values (:名字,:性别,:年龄)";
OleDbCommand oleCmd = new OleDbCommand(strCmd, oleConn);
//添加上传内容
oleCmd.Parameters.AddWithValue("名字", "李四");
oleCmd.Parameters.AddWithValue("性别", "男");
oleCmd.Parameters.AddWithValue("年龄", 23);
oleCmd.ExecuteNonQuery();
oleConn.Close();
bolReturn = true;
}
catch (Exception ex)
{
MessageBox.Show("添加失败", "数据库提示");
}
return bolReturn;
}
2:添加效果如下所示: