ConnectedApplication.cpp
上传用户:sz0451
上传日期:2022-07-29
资源大小:256k
文件大小:3k
源码类别:

.net编程

开发平台:

Visual C++

  1. // This is the main project file for VC++ application project 
  2. // generated using an Application Wizard.
  3. #include "stdafx.h"
  4. #using <mscorlib.dll>
  5. #using <System.dll>        // For Console I/O
  6. #using <System.Data.dll>   // For ADO.NET
  7. using namespace System;
  8. using namespace System::Data;              // Generic ADO.NET definitions
  9. using namespace System::Data::SqlClient;   // Specific definitions for SQL Server data provider
  10. // This is the entry point for this application
  11. #ifdef _UNICODE
  12. int wmain(void)
  13. #else
  14. int main(void)
  15. #endif
  16. {
  17. // Create a SqlConnection object
  18. SqlConnection * cnPubs = new SqlConnection();
  19. // Set the connection string
  20. cnPubs->ConnectionString = S"data source=(local);integrated security=true;initial catalog=Pubs";
  21. try
  22. {
  23. // Try to open the connection
  24. cnPubs->Open();
  25.     Console::WriteLine(S"Connected to database successfully!");
  26. // Create a command object
  27. SqlCommand * cmTitles = new SqlCommand();
  28. cmTitles->CommandText = S"SELECT COUNT(*) FROM Titles";
  29. cmTitles->CommandType = CommandType::Text;
  30. cmTitles->Connection = cnPubs;
  31. // Execute a SQL statement that returns a scalar value, and display results
  32. Object * numberOfTitles = cmTitles->ExecuteScalar();
  33.         Console::Write(S"Number of titles: ");
  34. Console::WriteLine(numberOfTitles);
  35. // Execute a SQL statement that modifies the database, and display results
  36. cmTitles->CommandText = S"UPDATE titles SET price = price * 1.05 WHERE price IS NOT NULL";
  37. int rowsAffected = cmTitles->ExecuteNonQuery();
  38.         Console::Write(S"Number of titles increased in price: ");
  39. Console::WriteLine(rowsAffected);
  40. // Execute a SQL statement that queries the database
  41. cmTitles->CommandText = S"SELECT title, price FROM titles";
  42. // Execute the query
  43. SqlDataReader * reader = cmTitles->ExecuteReader();
  44. // Display the query results
  45. Console::WriteLine(S"n---------------------------------------------");
  46. while (reader->Read())
  47. {
  48. Console::Write(reader->GetString(0));
  49. Console::Write(S", ");
  50. if (reader->IsDBNull(1))
  51. Console::WriteLine(S"No price yet");
  52. else
  53. Console::WriteLine(reader->GetDecimal(1));
  54. }
  55. Console::WriteLine(S"---------------------------------------------");
  56. // Close the reader
  57. reader->Close();
  58. }
  59. catch (SqlException * Xcp)
  60. {
  61. Console::Write(S"Error occurred: ");
  62. Console::WriteLine(Xcp->Message);
  63. }
  64. // Close the connection
  65. if (cnPubs->State != ConnectionState::Closed)
  66. {
  67. cnPubs->Close();
  68. }
  69.     Console::WriteLine(S"The database connection is now closed");
  70. }