|
| 1 | +// JSONConsoleApp: End-to-end demo of working with |
| 2 | +// SQL Server JSON datatype via Microsoft.Data.SqlClient |
| 3 | +// |
| 4 | +// Highlights: |
| 5 | +// - Creates a demo table with a JSON column |
| 6 | +// - Inserts JSON via string and via SqlJson |
| 7 | +// - Inserts JSON from a file |
| 8 | +// - Reads JSON back with GetString and GetSqlJson |
| 9 | +// - Demonstrates a stored procedure with a JSON OUTPUT parameter |
| 10 | +// |
| 11 | +// Requirements: |
| 12 | +// - SQL Server 2025 and above. |
| 13 | +// - Microsoft.Data.SqlClient (6.1.2 and above) |
| 14 | +//<Snippet1> |
| 15 | +using System.Data; |
| 16 | +using Microsoft.Data; |
| 17 | +using Microsoft.Data.SqlClient; |
| 18 | +using Microsoft.Data.SqlTypes; |
| 19 | +using System.Text.Json; |
| 20 | + |
| 21 | +class Program |
| 22 | +{ |
| 23 | + // NOTE: For production, prefer Encrypt=True and TrustServerCertificate=False with a valid cert. |
| 24 | + private const string connString = @"Server=tcp:localhost;Database=Demo2;Integrated Security=True;Encrypt=true;TrustServerCertificate=true;"; |
| 25 | + private const string tableName = "jsonTab"; |
| 26 | + private const string createBody = "(Id INT IDENTITY(1,1) PRIMARY KEY, Data json NULL)"; |
| 27 | + |
| 28 | + static void Main(string[] args) |
| 29 | + { |
| 30 | + CreateTable(connString, tableName, createBody); |
| 31 | + |
| 32 | + InsertJSONWithStr(connString); |
| 33 | + InsertJSONWithSqlJson(connString); |
| 34 | + InsertJSONFile(connString); |
| 35 | + ReadJSONWithGetString(connString); |
| 36 | + ReadJSONWithSqlJson(connString); |
| 37 | + ReadJsonWithSPParam(connString); |
| 38 | + } |
| 39 | + |
| 40 | + #region Helper Methods to Create/Drop Table and stored procedures |
| 41 | + public static void CreateSP(string connString, string spName, string spBody) |
| 42 | + { |
| 43 | + DropSP(connString, spName); |
| 44 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 45 | + { |
| 46 | + sqlConnection.Open(); |
| 47 | + string spCreate = "CREATE PROCEDURE " + spName + spBody; |
| 48 | + using (SqlCommand command = sqlConnection.CreateCommand()) |
| 49 | + { |
| 50 | + command.CommandText = spCreate; |
| 51 | + command.ExecuteNonQuery(); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public static void DropSP(string connString, string spName) |
| 57 | + { |
| 58 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 59 | + { |
| 60 | + sqlConnection.Open(); |
| 61 | + using (SqlCommand cmd = new SqlCommand(string.Format("IF (OBJECT_ID('{0}') IS NOT NULL) \n DROP PROCEDURE {0}", spName), sqlConnection)) |
| 62 | + { |
| 63 | + cmd.ExecuteNonQuery(); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private static void CreateTable(string connString, string tableName, string createBody) |
| 69 | + { |
| 70 | + DropTable(connString, tableName); |
| 71 | + string tableCreate = "CREATE TABLE [" + tableName + "]" + createBody; |
| 72 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 73 | + { |
| 74 | + sqlConnection.Open(); |
| 75 | + using (SqlCommand command = sqlConnection.CreateCommand()) |
| 76 | + { |
| 77 | + command.CommandText = tableCreate; |
| 78 | + command.ExecuteNonQuery(); |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + private static void DropTable(string connString, string tableName) |
| 84 | + { |
| 85 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 86 | + { |
| 87 | + sqlConnection.Open(); |
| 88 | + using (SqlCommand cmd = new SqlCommand(string.Format("IF (OBJECT_ID('{0}') IS NOT NULL) \n DROP TABLE {0}", tableName), sqlConnection)) |
| 89 | + { |
| 90 | + cmd.ExecuteNonQuery(); |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + #endregion |
| 96 | + |
| 97 | + private static void ReadJsonWithSPParam(string connString) |
| 98 | + { |
| 99 | + Console.WriteLine("Reading JSON with Stored Procedure and Output Parameter"); |
| 100 | + |
| 101 | + // Create stored procedure for reading JSON value |
| 102 | + string storedProcName = "GetJsonData"; |
| 103 | + string tableName = "jsonTab"; |
| 104 | + string createSP = $@" |
| 105 | + @id int, |
| 106 | + @jsonData json OUTPUT |
| 107 | + AS |
| 108 | + BEGIN |
| 109 | + SELECT @jsonData = (SELECT Data FROM {tableName} WHERE Id = @id) |
| 110 | + END;"; |
| 111 | + CreateSP(connString, storedProcName, createSP); |
| 112 | + |
| 113 | + using (SqlConnection connection = new SqlConnection(connString)) |
| 114 | + { |
| 115 | + connection.Open(); |
| 116 | + string procName = "GetJsonData"; |
| 117 | + |
| 118 | + // Execute Stored Procedure |
| 119 | + using (SqlCommand spCommand = new SqlCommand(procName, connection)) |
| 120 | + { |
| 121 | + spCommand.CommandType = CommandType.StoredProcedure; |
| 122 | + spCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int) { Direction = ParameterDirection.Input, Value = 1 }); |
| 123 | + |
| 124 | + //Use SqlDbType.Json depending on the dotnet version or or SqlDbTypeExtensions.Json |
| 125 | + SqlParameter outputParam = new SqlParameter("@jsonData", SqlDbTypeExtensions.Json) { Direction = ParameterDirection.Output }; |
| 126 | + spCommand.Parameters.Add(outputParam); |
| 127 | + spCommand.ExecuteNonQuery(); |
| 128 | + Console.WriteLine($"JSON Data from SP: {outputParam.Value}"); |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + private static void ReadJSONWithSqlJson(string connString) |
| 134 | + { |
| 135 | + Console.WriteLine("Reading JSON into SqlJson"); |
| 136 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 137 | + { |
| 138 | + sqlConnection.Open(); |
| 139 | + using (SqlCommand command = new SqlCommand("SELECT Data FROM jsonTab", sqlConnection)) |
| 140 | + { |
| 141 | + using (SqlDataReader reader = command.ExecuteReader()) |
| 142 | + { |
| 143 | + while (reader.Read()) |
| 144 | + { |
| 145 | + if (!reader.IsDBNull(0)) |
| 146 | + { |
| 147 | + //Read JSON with GetString |
| 148 | + var jsonData = reader.GetSqlJson(0); |
| 149 | + Console.WriteLine($"JSON Data: {jsonData}"); |
| 150 | + } |
| 151 | + else |
| 152 | + { |
| 153 | + Console.WriteLine("JSON Data: NULL"); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + private static void ReadJSONWithGetString(string connString) |
| 162 | + { |
| 163 | + Console.WriteLine("Reading JSON with GetString"); |
| 164 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 165 | + { |
| 166 | + sqlConnection.Open(); |
| 167 | + using (SqlCommand command = new SqlCommand("SELECT Data FROM jsonTab", sqlConnection)) |
| 168 | + { |
| 169 | + using (SqlDataReader reader = command.ExecuteReader()) |
| 170 | + { |
| 171 | + while (reader.Read()) |
| 172 | + { |
| 173 | + if (!reader.IsDBNull(0)) |
| 174 | + { |
| 175 | + //Read JSON with GetString |
| 176 | + string jsonData = reader.GetString(0); |
| 177 | + Console.WriteLine($"JSON Data: {jsonData}"); |
| 178 | + } |
| 179 | + else |
| 180 | + { |
| 181 | + Console.WriteLine("JSON Data: NULL"); |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + private static void InsertJSONFile(string connString) |
| 190 | + { |
| 191 | + Console.WriteLine("Inserting JSON File"); |
| 192 | + var dummyData = new |
| 193 | + { |
| 194 | + name = "Keith Johnson", |
| 195 | + age = 36, |
| 196 | + city = "Boston" |
| 197 | + }; |
| 198 | + |
| 199 | + string jsonString = JsonSerializer.Serialize(dummyData, new JsonSerializerOptions { WriteIndented = true }); |
| 200 | + string jsonFile = "dummyData.json"; |
| 201 | + if (File.Exists(jsonFile)) |
| 202 | + { |
| 203 | + File.Delete(jsonFile); |
| 204 | + } |
| 205 | + File.WriteAllText(jsonFile, jsonString); |
| 206 | + |
| 207 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 208 | + { |
| 209 | + sqlConnection.Open(); |
| 210 | + using (SqlCommand command = new SqlCommand("INSERT INTO jsonTab (Data) VALUES (@jsonData)", sqlConnection)) |
| 211 | + { |
| 212 | + SqlParameter jsonParam = new SqlParameter("@jsonData", SqlDbTypeExtensions.Json); |
| 213 | + using (StreamReader jsonFileReader = File.OpenText(jsonFile)) |
| 214 | + { |
| 215 | + jsonParam.Value = jsonFileReader; |
| 216 | + command.Parameters.Add(jsonParam); |
| 217 | + command.ExecuteNonQuery(); |
| 218 | + } |
| 219 | + } |
| 220 | + } |
| 221 | + if (File.Exists(jsonFile)) |
| 222 | + { |
| 223 | + File.Delete(jsonFile); |
| 224 | + } |
| 225 | + } |
| 226 | + |
| 227 | + private static void InsertJSONWithSqlJson(string connString) |
| 228 | + { |
| 229 | + Console.WriteLine("Inserting JSON with SqlJson"); |
| 230 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 231 | + { |
| 232 | + sqlConnection.Open(); |
| 233 | + using (SqlCommand command = new SqlCommand("INSERT INTO jsonTab (Data) VALUES (@jsonData)", sqlConnection)) |
| 234 | + { |
| 235 | + //Insert non-null value with SqlJson |
| 236 | + string jsonData = @"{ ""name"": ""Jane Smith"", ""age"": 25, ""city"": ""Los Angeles"" }"; |
| 237 | + SqlJson sqlJsonObj = new SqlJson(jsonData); |
| 238 | + SqlParameter jsonParam = new SqlParameter("@jsonData", SqlDbTypeExtensions.Json) { Value = sqlJsonObj }; |
| 239 | + command.Parameters.Add(jsonParam); |
| 240 | + command.ExecuteNonQuery(); |
| 241 | + command.Parameters.Clear(); |
| 242 | + |
| 243 | + //Insert null value with SqlJson |
| 244 | + sqlJsonObj = new SqlJson(); |
| 245 | + jsonParam.Value = sqlJsonObj; |
| 246 | + command.Parameters.Add(jsonParam); |
| 247 | + command.ExecuteNonQuery(); |
| 248 | + } |
| 249 | + } |
| 250 | + } |
| 251 | + |
| 252 | + private static void InsertJSONWithStr(string connString) |
| 253 | + { |
| 254 | + Console.WriteLine("Inserting JSON with string"); |
| 255 | + string insertQuery = "INSERT INTO jsonTab (Data) VALUES (@jsonData)"; |
| 256 | + |
| 257 | + using (SqlConnection sqlConnection = new SqlConnection(connString)) |
| 258 | + { |
| 259 | + sqlConnection.Open(); |
| 260 | + using (SqlCommand command = new SqlCommand(insertQuery, sqlConnection)) |
| 261 | + { |
| 262 | + //Insert non-null value |
| 263 | + string jsonData = @"{ ""name"": ""John Doe"", ""age"": 30, ""city"": ""New York"" }"; |
| 264 | + command.Parameters.AddWithValue("@jsonData", jsonData); |
| 265 | + command.ExecuteNonQuery(); |
| 266 | + command.Parameters.Clear(); |
| 267 | + |
| 268 | + //Insert null value |
| 269 | + command.Parameters.AddWithValue("@jsonData", DBNull.Value); |
| 270 | + command.ExecuteNonQuery(); |
| 271 | + } |
| 272 | + } |
| 273 | + } |
| 274 | +} |
| 275 | +//</Snippet1> |
| 276 | + |
0 commit comments