C#简单连接sql数据库的方法

时间:2021-05-20

本文实例讲述了C#简单连接sql数据库的方法。分享给大家供大家参考,具体如下:

using System;using System.Collections.Generic;using System.Text;//数据库操作对象库using System.Data;using System.Data.SqlClient;using worddic;namespace testDB{ class Program { static void Main(string[] args) { //char[] array = new char[2] ; string [] a = new string[2]; FileOp words = new FileOp(); words.openfile("worddic.txt"); words.getwords(ref a); string strConn = "Data Source=HYPER-V-WIN2003\\SQLSRV2005;Initial Catalog=Mytest;User ID=sa;Password=sa"; SqlConnection conn = null; SqlCommand sqlCmd = null; try { //创建connection对象 conn = new SqlConnection(strConn); //打开数据库连接 conn.Open(); //创建Transac Sql命令对象 sqlCmd = conn.CreateCommand(); //创建建表语句 //sqlCmd.CommandText = "create table wordlist(wrongwords varchar(30),rightwords varchar(30),sign char(20),)"; //sqlCmd.ExecuteScalar(); while (a[0] != null) { sqlCmd.CommandText ="insert into wordlist(wrongwords,rightwords,sign) values('" + a[0] + "','" + a[1] + "',1 )"; sqlCmd.ExecuteScalar(); a[0] = null; a[1] = null; words.getwords(ref a); } words.fileclose(); Console.WriteLine(); //打印所有记录 } catch (SqlException e) { Console.WriteLine(e.Message); } finally { conn.Close(); } Console.WriteLine("程序结束,按任意键退出"); Console.ReadKey(); } }}

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》

希望本文所述对大家C#程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章