0 / 0 / 0
Регистрация: 21.10.2017
Сообщений: 40
1

Insert: column name or number of supplied values does not match table definition

27.11.2018, 01:43. Показов 4366. Ответов 4
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый вечер! На форме имеется 11 полей ввода: 7 string(2 comboBox & 5 textBox), 3 int, 1 date.
Столкнулся с проблемой при попытки добавления элементов в таблицу, выводит ошибку

Insert: column name or number of supplied values does not match table definition


Хотя я уверен, что типы таблици соответствуют моим переменным

Insert: column name or number of supplied values does not match table definition


Вот код:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private void Button_add_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                String id = Textbox_id.Text.ToString();
                int eid = Int32.Parse(id); 
                String surname = Textbox_surname.Text.ToString();
                String name = Textbox_name.Text.ToString();
                String birthday = Textbox_birth.Text.ToString();
                DateTime date = DateTime.Parse(birthday);
                String gender = comboBox_gender.SelectedIndex.ToString();
                String univer = comboBox_univer.SelectedIndex.ToString();
                String email = Textbox_email.Text.ToString();
                String tent = Textbox_tent.Text.ToString();
                int tent_num = Int32.Parse(tent);
                String teacher = Textbox_teacher.Text.ToString();
                String experiment = Textbox_exp.Text.ToString();
                String points = Textbox_points.Text.ToString();
                int point = Int32.Parse(points);
 
               
                string qry = "insert into Students values('"+eid+"','"+surname+ "','" + name + "','" + date + "','" + gender + "','" + univer + "','" + email + "','" + tent_num + "','" + teacher + "','" + experiment + "','" + point + "')";
                SqlCommand sc = new SqlCommand(qry,con);
                int i = sc.ExecuteNonQuery();
                //if (i>=1)
                //MessageBox.Show(i+"Student Registed"+name);
                //else
                //    MessageBox.Show("Student Not Registed" + name);
 
                con.Close();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
 
            }
        }
Надеюсь на вашу помощь)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
27.11.2018, 01:43
Ответы с готовыми решениями:

Cannot insert the value NULL into column 'Id', table '.dbo.Records';column does not allow nulls
Уважаемые, т.к. мой мозг не способен понять, почему вылазит данное исключение, когда я добавляю...

insert into table values (select....
Здравствуйте, скажите, как заставить работать следующий запрос: insert into tg3.dbo.tg3hour values...

Fatal error - Invalid parameter number: number of bound variables does not match number of tokens'
$pass = md5($_POST); $email = $_POST; $login = $_POST; $sex = $_POST;...

Cannot modify a column which maps to a non key-preserved table, insert into
Есть две таблицы: create table slimnicas( s_ID number constraint Ierob_pa PRIMARY KEY, -- <<<...

4
79 / 102 / 44
Регистрация: 12.05.2015
Сообщений: 476
27.11.2018, 06:22 2
IT_shnik, используйте параметризованные запросы и таких проблем не будет.
1
54 / 48 / 31
Регистрация: 14.04.2015
Сообщений: 273
27.11.2018, 09:06 3
IT_shnik, 100% ошибка в запросе. Соглашусь с Tessio, используй параметризованные запросы.


C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public void driverInsert(string FIO, string Certification)
        {
            using (connect = new OleDbConnection(connectString))
            {
                try
                {
                    command = new OleDbCommand("INSERT INTO [Driver] ([FIO], [Certification])" +
                    "VALUES (@FIO, @Certification)", connect);
 
                    command.Parameters.AddWithValue("@FIO", FIO);
                    command.Parameters.AddWithValue("@Certification", Certification);
                    
                    connect.Open();
                    if (command.ExecuteNonQuery() == 1)
                    {
                        MessageBox.Show("Запись добавлена", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    connect.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

Пример функции добавления данных в БД
1
784 / 615 / 273
Регистрация: 04.08.2015
Сообщений: 1,707
27.11.2018, 10:40 4
Цитата Сообщение от IT_shnik Посмотреть сообщение
Хотя я уверен, что типы таблици соответствуют моим переменным
Цитата Сообщение от IT_shnik Посмотреть сообщение
insert into Students values('"+eid+"',
Одинарные кавычки превращают любой тип данных в текст.
0
Администратор
Эксперт .NET
16989 / 13348 / 5209
Регистрация: 17.03.2014
Сообщений: 27,295
Записей в блоге: 1
27.11.2018, 21:05 5
IT_shnik, при INSERT запросе без указания колонок нужно указывать данные для всех колонок таблицы.У тебя же в таблице 12 колонок, а в запросе 11. Нужно добавить NULL для последней колонки. И, да, как уже посоветовали - следует использовать параметры.
1
27.11.2018, 21:05
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
27.11.2018, 21:05
Помогаю со студенческими работами здесь

Invalid parameter number: number of bound variables does not match number of tokens
Не могу решить ошибку: Invalid parameter number: number of bound variables does not match number...

Invalid parameter number: number of bound variables does not match number of tokens
запрос $conn = connect_to_db(); $stmt = $conn->prepare("INSERT INTO brandaccounts...

Ошибка после подключения к БД "The column prefix 'Included' does not match with a table name"
есть файл connection.cs using System; using System.Collections.Generic; using System.Text;...

Number of variables doesn't match number of parameters in prepared statement
Собственно, код $query = mysqli_prepare($db, "SELECT * FROM `users_db` WHERE `user_name`='?' ||...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru