c# add data to firebird database

2019-06-11 04:56发布

There is code that I use to pass new data to Database (firebird):

FbConnection fbCon = new FbConnection(csb.ToString());
FbDataAdapter fbDAdapter = new FbDataAdapter("SELECT ID,name,score FROM players",fbCon);
FbCommandBuilder Cmd = new FbCommandBuilder(fbDAdapter);
DataSet DSet = new DataSet();
fbDAdapter.Fill(DSet);
DataRow rw = DSet.Tables[0].NewRow();
rw["ID"] = zID + 1;
rw["name"] = var;
rw["score"] = score;
DSet.Tables[0].Rows.Add(rw);
fbDAdapter.Update(DSet);

Maybe you can suggest better algorithm, or this is pretty good?

2条回答
做自己的国王
2楼-- · 2019-06-11 05:29

This way is OK, you are using a command builder that do a lot of work for, you can simply translate the above code into an insert command to execute directly on the database table :

  FbConnection fbCon = new FbConnection(csb.ToString());
  FbCommand fbCom = new FbCommand("INSERT INTO players(ID,name,score) VALUES (@id,@name,@score)", fbCon);
  fbCom.Parameters.AddWithValue("id", zID + 1);
  fbCom.Parameters.AddWithValue("name", var);
  fbCom.Parameters.AddWithValue("score", score);
  fbCom.ExecuteNonQuery();

In this way you avoid the command builder and loading the data into the Datatable, should be quite faster ...

查看更多
不美不萌又怎样
3楼-- · 2019-06-11 05:31

This is lighter for database:

      FbConnectionStringBuilder csb = new FbConnectionStringBuilder( );
      csb.ServerType = FbServerType.Default;
      csb.Database = Settings.Default.LastBDPath;
      csb.Password = Settings.Default.LastBDPassword; //            "masterkey";
      csb.UserID = Settings.Default.LastBDUser;       //            "SYSDBA";
      connection = new FbConnection( csb.ToString( ) );

      connection.Open( ); 

      string scriptLine = string.Format("INSERT INTO TABLE (Id, Name, Score) values ({0}, '{1}', {2}", zId+1, var, score) ; 
      FBCommand command = new FbCommand( scriptline, connection );
      command.ExecuteNonQuery( );

For a select:

string sql = string.Format("select * from table where name='{0}';", your_name);

FbCommand command = new FbCommand( sql ), connection );
FbDataReader reader = command.ExecuteReader( );
while ( reader.Read( ) )
{
    for ( int i=0; i<reader.FieldCount; i++ )
    {
         objects[i].Add( reader.GetValue( i ) );
    }
}
查看更多
登录 后发表回答