C#与VB.ENT更新Access数据库
C#与VB.ENT更新Access数据库
-
C#更新Access数据库
1:C#更新Access数据库,其代码如下:
/// <summary>
///更新数据库
/// </summary>
/// <param name="filepath">数据库文件的路径</param>
/// <returns>true:更新成功</returns>
public bool DataUpdate(string filepath)
{
bool bolReturn = false;
try
{
//连接数据库
OleDbConnection oleCon = getConnection(filepath);
//打开数据库
if (oleCon.State == ConnectionState.Open) { oleCon.Close(); }
oleCon.Open();
//执行语句
string strCmd = "Update Administrator set ";
strCmd += "名字='李四',";
strCmd += "性别='女',";
strCmd += "年龄='55' where 名字='李四'";
/*从此处可看到,我们设置数据库时最好设置一个与数据库内容无关的字段(例如id)作为主键()且不能重复,以方便修改数据库,
像此数据库只有"名字","性别","年龄"三列,由于没有添加其他列,导致在更新信息时不能更新全部,且如果以字段名"名字"作为
索引找到更新的信息时,存在如果有两个重复的名字,就会导致两条信息全部被更新。所以,创建数据库时最好创建一个与数据
库内容无关且不能重复的字段作为主键之一,方便与后期的操作。
*/
OleDbCommand oleCmd = new OleDbCommand(strCmd, oleCon);
oleCmd.ExecuteNonQuery();
oleCon.Close();
bolReturn = true;
}
catch (Exception ex)
{
MessageBox.Show("更新失败", "数据库提示");
}
return bolReturn ;
}
2:更新效果如下所示:
- VB.NET更新Access数据库
1:VB.NET更新Access数据库,其代码如下:
''' <summary>
''' 更新数据库
''' </summary>
''' <param name="filepath">数据库的路径</param>
''' <returns>true:更新成功</returns>
''' <remarks></remarks>
Public Function DataUpdate(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 = "update Administrator set "
strCmd += "名字='张三',"
strCmd += "性别='男',"
strCmd += "年龄=100 where 名字='张三'"
Dim oleCmd As OleDbCommand = New OleDbCommand(strCmd, oleCon)
oleCmd.ExecuteNonQuery()
oleCon.Close()
bolReturn = True
Catch ex As Exception
MessageBox.Show("更新失败", "数据库提示")
End Try
Return bolReturn
End Function
2:更新效果如图所示:


浙公网安备 33010602011771号