ConnectedApplication.cpp
上传用户:sz0451
上传日期:2022-07-29
资源大小:256k
文件大小:3k
- // This is the main project file for VC++ application project
- // generated using an Application Wizard.
- #include "stdafx.h"
- #using <mscorlib.dll>
- #using <System.dll> // For Console I/O
- #using <System.Data.dll> // For ADO.NET
- using namespace System;
- using namespace System::Data; // Generic ADO.NET definitions
- using namespace System::Data::SqlClient; // Specific definitions for SQL Server data provider
- // This is the entry point for this application
- #ifdef _UNICODE
- int wmain(void)
- #else
- int main(void)
- #endif
- {
- // Create a SqlConnection object
- SqlConnection * cnPubs = new SqlConnection();
-
- // Set the connection string
- cnPubs->ConnectionString = S"data source=(local);integrated security=true;initial catalog=Pubs";
-
- try
- {
- // Try to open the connection
- cnPubs->Open();
- Console::WriteLine(S"Connected to database successfully!");
- // Create a command object
- SqlCommand * cmTitles = new SqlCommand();
- cmTitles->CommandText = S"SELECT COUNT(*) FROM Titles";
- cmTitles->CommandType = CommandType::Text;
- cmTitles->Connection = cnPubs;
- // Execute a SQL statement that returns a scalar value, and display results
- Object * numberOfTitles = cmTitles->ExecuteScalar();
- Console::Write(S"Number of titles: ");
- Console::WriteLine(numberOfTitles);
- // Execute a SQL statement that modifies the database, and display results
- cmTitles->CommandText = S"UPDATE titles SET price = price * 1.05 WHERE price IS NOT NULL";
- int rowsAffected = cmTitles->ExecuteNonQuery();
- Console::Write(S"Number of titles increased in price: ");
- Console::WriteLine(rowsAffected);
- // Execute a SQL statement that queries the database
- cmTitles->CommandText = S"SELECT title, price FROM titles";
- // Execute the query
- SqlDataReader * reader = cmTitles->ExecuteReader();
- // Display the query results
- Console::WriteLine(S"n---------------------------------------------");
- while (reader->Read())
- {
- Console::Write(reader->GetString(0));
- Console::Write(S", ");
- if (reader->IsDBNull(1))
- Console::WriteLine(S"No price yet");
- else
- Console::WriteLine(reader->GetDecimal(1));
- }
- Console::WriteLine(S"---------------------------------------------");
-
- // Close the reader
- reader->Close();
- }
- catch (SqlException * Xcp)
- {
- Console::Write(S"Error occurred: ");
- Console::WriteLine(Xcp->Message);
- }
- // Close the connection
- if (cnPubs->State != ConnectionState::Closed)
- {
- cnPubs->Close();
- }
- Console::WriteLine(S"The database connection is now closed");
- }