4 // To Test PgSqlConnection and PgSqlCommand by connecting
5 // to a PostgreSQL database
6 // and then executing an INSERT SQL statement
9 // change strings to your database, userid, tables, etc...:
14 // mcs TestPgSqlInsert.cs -r System.Data
15 // mint TestPgSqlInsert.exe
18 // Rodrigo Moya (rodrigo@ximian.com)
19 // Daniel Morgan (danmorg@sc.rr.com)
21 // (C) Ximian, Inc 2002
26 using Mono.Data.PostgreSqlClient;
28 namespace TestSystemDataPgSqlClient
33 static void Main(string[] args) {
34 PgSqlConnection conn = null;
35 PgSqlCommand cmd = null;
36 PgSqlTransaction trans = null;
38 int rowsAffected = -1;
40 String connectionString = "";
41 String insertStatement = "";
42 String deleteStatement = "";
50 "insert into NoSuchTable " +
52 "values ('beer', 'Beer for All!') ";
55 "delete from sometable " +
56 "where tid = 'beer' ";
59 // Connect to a PostgreSQL database
60 Console.WriteLine ("Connect to database...");
61 conn = new PgSqlConnection(connectionString);
65 Console.WriteLine ("Begin Transaction...");
66 trans = conn.BeginTransaction();
68 // create SQL DELETE command
69 Console.WriteLine ("Create Command initializing " +
70 "with an DELETE statement...");
71 cmd = new PgSqlCommand (deleteStatement, conn);
73 // execute the DELETE SQL command
74 Console.WriteLine ("Execute DELETE SQL Command...");
75 rowsAffected = cmd.ExecuteNonQuery();
76 Console.WriteLine ("Rows Affected: " + rowsAffected);
78 // change the SQL command to an SQL INSERT Command
79 Console.WriteLine ("Now use INSERT SQL Command...");
80 cmd.CommandText = insertStatement;
82 // execute the INSERT SQL command
83 Console.WriteLine ("Execute INSERT SQL Command...");
84 rowsAffected = cmd.ExecuteNonQuery();
85 Console.WriteLine ("Rows Affected: " + rowsAffected);
87 // if successfull at INSERT, commit the transaction,
88 // otherwise, do a rollback the transaction using
90 Console.WriteLine ("Commit transaction...");
93 // Close connection to database
94 Console.WriteLine ("Close database connection...");
97 Console.WriteLine ("Assuming everything " +
99 Console.WriteLine ("Verify data in database to " +
100 "see if row is there.");
102 catch(PgSqlException e) {
103 // Display the SQL Errors and Rollback the database
104 Console.WriteLine("PgSqlException caught: " +
108 Console.WriteLine("Database has been Rolled back!");
113 if(conn.State == ConnectionState.Open)