111,129
社区成员
发帖
与我相关
我的任务
分享
protected void CreateTable()
{
string sqlconn = "server=.; database=dbName; uid=sa; pwd=sa";//连接字
//首先判断表是否存在,在创建表
string strSql = string.Format(@"
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[表名]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[表名]
create table 表名 (id int primary key ,name varchar(100) not null )");
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(sqlconn))
{
conn.Open();
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strSql, conn))
{
cmd.ExecuteNonQuery();//执行
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//连接数据库对象,我用的sql server 本地连接的
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Hoter;Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
try
{
//在数据库中创建一个表,有俩个字段,把这句话写成字符串然后执行就可以了
String str = "create table aa(id int not null,name varchar(20) not null)";
SqlCommand com = new SqlCommand(str, con);
con.Open();//打开数据库
com.ExecuteNonQuery();//执行语句
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}