【发布时间】:2017-08-19 16:21:18
【问题描述】:
我正在尝试使用 Ado.Net 为我的作业编写“插入、删除、更新、显示”选项到 sql。由于我仍在学习,我的代码可能很长。请检查并告诉我我在哪里出错。代码进行到一半(仅为插入编码)。
我得到的错误是:
我的代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace Crud
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--What do you want to do?--");
Console.WriteLine(" 1. Insert\n 2. Update\n 3. Delete\n 4. Display\n");
int choice=int.Parse(Console.ReadLine());
if (choice == 1)
{
Console.Write("Enter Student name:");
string SName=Console.ReadLine();
Console.Write("Enter Student Mobile Number:");
string SMob = Console.ReadLine();
Console.Write("Enter student fees:");
string Sfees = Console.ReadLine();
Console.Write("Enter student course:");
string course=Console.ReadLine();
SqlConnection con = new SqlConnection("Data Source=Sachin-PC;Initial Catalog=ADOProject;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into focusstudents values(@name,@mobile,@fees,@course)";
cmd.Parameters.AddWithValue("@name",SName);
cmd.Parameters.AddWithValue("@mobile",SMob);
cmd.Parameters.AddWithValue("@fees", Sfees);
cmd.Parameters.AddWithValue("@course", course);
cmd.Connection = con;
con.Open();
int l = cmd.ExecuteNonQuery();
if (l > 0)
{
Console.WriteLine("Inserted Successfully");
cmd.CommandText = "select * from focusstudents";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
Console.Write("{0}{1}", dr[0], dr[1]);
}
}
else
{
Console.WriteLine("There is no data to display, add any data to be shown here");
}
}
con.Close();
}
Console.ReadKey();
}
}
}
【问题讨论】:
-
用适当的类型显式添加而不是
AddWithValue()。 -
focusstudents 表中有多余的列吗?列列表不匹配。更改“插入focusstudents(column1,column2..)值(...)”
-
我有一个主键列作为“id”
-
@sachin 是否像播种一样启用自动编号?如果没有,您必须启用它或通过 max id + 1
-
是的,这是错误。