Display name column is null ошибка sai

Describe the bug Unable to install latest Android APK on Android 12 To Reproduce Download APK Install APK Expected behavior App to be installed Screenshots Environment (please complete the followin...

Describe the bug
Unable to install latest Android APK on Android 12

To Reproduce
Download APK
Install APK

Expected behavior
App to be installed

Screenshots
Screenshot_20211124-111619

Environment (please complete the following information):

  • OS: Android 12
  • Version: V1.0.10-beta0

Additional context

Logs
Rooted installer error:

Device: google Pixel 6 | Not MIUI | Android 12 | Using FilterApkSource ApkSource implementation | SAI 4.5

com.aefyr.sai.model.filedescriptor.ContentUriFileDescriptor$BadContentProviderException: DISPLAY_NAME column is null
at com.aefyr.sai.model.filedescriptor.ContentUriFileDescriptor.name(ContentUriFileDescriptor.java:30)
at com.aefyr.sai.model.apksource.DefaultApkSource.getApkName(DefaultApkSource.java:42)
at com.aefyr.sai.model.apksource.SignerApkSource.getApkName(SignerApkSource.java:64)
at com.aefyr.sai.model.apksource.SignerApkSource.nextApk(SignerApkSource.java:46)
at com.aefyr.sai.model.apksource.FilterApkSource.nextApk(FilterApkSource.java:25)
at com.aefyr.sai.installer2.impl.shell.ShellSaiPackageInstaller.install(ShellSaiPackageInstaller.java:112)
at com.aefyr.sai.installer2.impl.shell.ShellSaiPackageInstaller.lambda$enqueueSession$0$ShellSaiPackageInstaller(ShellSaiPackageInstaller.java:93)
at com.aefyr.sai.installer2.impl.shell.-$$Lambda$ShellSaiPackageInstaller$VdI3y9AkULdYCG2o9afJnUCfQnA.run(Unknown Source:6)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:920)

Checklist

  • I have read the Contribution Guidelines.

I created an app and tried to install it on a physical device. The device immediately crash when I tried to run it. The app works fine in the emulator. My phone is Samsung Galaxy A30 (Android 11). The app’s minSdkVersion is 23 and targetSdkVersion is 31. My app lets user to create list of their subjects, grades and create alarm for their class.

Full error I got from my phone:

com.aefyr.sai.model.filedescriptor.ContentUriFileDescriptor$BadContentProviderException: DISPLAY_NAME column is null
    at com.aefyr.sai.model.filedescriptor.ContentUriFileDescriptor.name(ContentUriFileDescriptor.java:30)
    at com.aefyr.sai.model.apksource.DefaultApkSource.getApkLocalPath(DefaultApkSource.java:47)
    at com.aefyr.sai.model.apksource.FilterApkSource.getApkLocalPath(FilterApkSource.java:60)
    at com.aefyr.sai.model.apksource.FilterApkSource.nextApk(FilterApkSource.java:28)
    at com.aefyr.sai.installer2.impl.rootless.RootlessSaiPackageInstaller.install(RootlessSaiPackageInstaller.java:93)
    at com.aefyr.sai.installer2.impl.rootless.RootlessSaiPackageInstaller.lambda$enqueueSession$0$RootlessSaiPackageInstaller(RootlessSaiPackageInstaller.java:70)
    at com.aefyr.sai.installer2.impl.rootless.-$$Lambda$RootlessSaiPackageInstaller$ivyAcunEgIkYlu_dB2vN6MOWZPU.run(Unknown Source:6)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:923)

asked Jan 19, 2022 at 12:38

Nomel's user avatar

NomelNomel

1131 silver badge11 bronze badges

3

I think the reason is in Provider.
You cannot use some paths to files normally in Android 11 anymore.
Create a file provider.xml with something like

    <?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

Add necessary paths (Read about Content provider).
After this use Uri like:

 Uri fileUri = FileProvider.getUriForFile(
                requireContext(),
                BuildConfig.APPLICATION_ID + ".provider",
                file);

Add to Manifest:

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider" />
        </provider>

May you provide the code where this error appears?

answered Jan 19, 2022 at 15:59

Marina's user avatar

MarinaMarina

2422 silver badges10 bronze badges

2

Я создал приложение и попытался установить его на физическое устройство. Устройство сразу вылетает, когда я пытаюсь его запустить. Приложение отлично работает в эмуляторе. Мой телефон Samsung Galaxy A30 (Android 11). minSdkVersion приложения равно 23, а targetSdkVersion равно 31. Мое приложение позволяет пользователю создавать список своих предметов, оценок и создавать будильник для своего класса.

Полная ошибка, которую я получил с моего телефона:

com.aefyr.sai.model.filedescriptor.ContentUriFileDescriptor$BadContentProviderException: DISPLAY_NAME column is null
    at com.aefyr.sai.model.filedescriptor.ContentUriFileDescriptor.name(ContentUriFileDescriptor.java:30)
    at com.aefyr.sai.model.apksource.DefaultApkSource.getApkLocalPath(DefaultApkSource.java:47)
    at com.aefyr.sai.model.apksource.FilterApkSource.getApkLocalPath(FilterApkSource.java:60)
    at com.aefyr.sai.model.apksource.FilterApkSource.nextApk(FilterApkSource.java:28)
    at com.aefyr.sai.installer2.impl.rootless.RootlessSaiPackageInstaller.install(RootlessSaiPackageInstaller.java:93)
    at com.aefyr.sai.installer2.impl.rootless.RootlessSaiPackageInstaller.lambda$enqueueSession$0$RootlessSaiPackageInstaller(RootlessSaiPackageInstaller.java:70)
    at com.aefyr.sai.installer2.impl.rootless.-$$Lambda$RootlessSaiPackageInstaller$ivyAcunEgIkYlu_dB2vN6MOWZPU.run(Unknown Source:6)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:923)

1 ответ

Думаю причина в провайдере. Вы больше не можете использовать некоторые пути к файлам, как обычно в Android 11. Создайте файл provider.xml с чем-то вроде

    <?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

Добавьте необходимые пути (Читайте о Контент-провайдере). После этого используйте Uri, например:

 Uri fileUri = FileProvider.getUriForFile(
                requireContext(),
                BuildConfig.APPLICATION_ID + ".provider",
                file);

Добавить в манифест:

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider" />
        </provider>

Можете ли вы предоставить код, где появляется эта ошибка?


0

Marina
19 Янв 2022 в 18:59

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

This page is for when you encounter a problem with a source or the app.

# What are some common issues?

If error-specific instructions didn’t help or your error isn’t on the list, go through Diagnosis.

# Diagnosis

  • Verify your extensions are up to date (

    explore

    BrowseExtensions, make sure no extensions have an Update button).

  • Check if Tachiyomi has an update (

    more_horiz

    More

    info

    About then tap Check for updates).

  • Manually refresh the manga you are having issues with by dragging down.
  • Check other manga from the source.
  • Verify that WebView is updated.
  • Try opening the manga in

    public

    WebView . If there is a Cloudflare protection, wait for it to load. If there is a CAPTCHA, solve it and see if it helped.

  • Change your internet connection (switch to Wi-Fi, mobile data or a VPN, use a «What’s my IP» site to confirm your IP has changed), then try again.
  • Ask other users to try the action that gives you the error.
  • Check if the source is either down, or is having issues in a browser.
  • Press the retry button in the middle of your manga page if one exists.
  • Try the following at

    more_horiz

    More

    settings

    Settings

    code

    Advanced

    • Clear Cache
    • Clear Cookies
    • Clear Database
    • DNS over HTTPS
  • If your downloads are getting stuck, try deleting the queue and trying again.
  • Force close Tachiyomi and reopen it.

An extension update may fix your issue. Wait or check for an extension update if you have not already. There are no ETAs for updates.

If any of these solutions help, go to it only happens to me.
If it is not just you, go to everyone is having this problem.

If none of these solutions help, try asking in our Discord Server (opens new window). Check #status-updates first to see if your issue is known. State your app version and the source, manga, and chapter with the problem if it is not listed.

# It only happens to me

You may be getting a Cloudflare protection, may have been IP-banned, or encountered some other counter-measure that website owners deploy against programs like Tachiyomi. If that is the case, there is probably nothing that Tachiyomi can do to solve it. Some of them (like Cloudflare) have to be manually solved, and some are temporary (IP bans).

Workarounds that can the lower chance of an issue happening again:

  • Don’t use downloads with the source.
  • Have less manga in your library from the source.

The above are imprecise and fuzzy rules because each site has its non-public limits and triggers.

# Everyone is having this problem

If the site is reachable and fully functional, there may be an issue with the extension or app.

  1. Have a look at open issues for the app (opens new window) and/or extensions (opens new window).
  2. It may have been fixed already but not released yet, so look at closed issues (app (opens new window) / extensions (opens new window)) issues as well.
  3. If you can’t find the issue there, open a new one.

If the site is not reachable or has issues, all you can do is wait for the site to become functional again.

# Solving Cloudflare issues

Cloudflare is an anti-bot mechanism. Some sources intentionally have a higher Cloudflare protection level to block apps like Tachiyomi. You can try the following suggestions to help resolve Cloudflare challenges. If they don’t work, migrate to other sources or wait until they lower their protection.

# Loading the website in WebView

Try to load the website in WebView. Note that WebView is not the same as using your browser.

How to open WebView

  1. Go to

    explore

    Browse in the bottom navbar.

  2. Press the source you would like to access.
  3. Press the

    public

    WebView icon in the top toolbar.

  4. Complete a CAPTCHA if one is shown.
  5. Once done, press the X at the top left to return.

You may need to try this multiple times. You can also try pressing the

more_vert

Overflow icon, opening the website in your regular browser, then checking for a CAPTCHA there.

Some sources may have more advanced Cloudflare protection. If you are facing issues, try the following options.

# Clearing WebView data

GUIDE

  1. In the

    public

    WebView screen, try «Clear cookies» then «Refresh» from the

    more_vert

    Overflow menu.

  2. Go to

    more_horiz

    More in the bottom navbar, then

    settings

    Settings

    code

    Advanced , then select «Clear WebView data».

# Changing your user agent

A user agent string helps websites identify information about the requester. While some sources have user agent strings set, most rely on the default value set in the app.

GUIDE

  1. Go to

    more_horiz

    More in the bottom navbar, then

    settings

    Settings

    code

    Advanced .

  2. Change the Default user agent string setting to a different one. This website (opens new window) is a decent reference.
  3. Restart the app and try accessing the source again.

# Update WebView

To update WebView, you need to find what WebView implementation is used on your device. In general, default implementation depends on the Android version as follows:

  • Android 10.0 and up — Android System WebView (opens new window).
  • Android from 7.0 to 9.0 — Google Chrome (opens new window).
  • Android 6.0.1 and below — Android System WebView (opens new window).

# Unable to install the app or extensions

Try installing Split APK Installer (opens new window) from the Google Play Store, then use it to try and install the affected APK. Split APK Installer will tell you why the APK is uninstallable, or it will install the APK for you. Some common errors are listed below.

# Getting Logcats and Crash Logs

To dump crash logs following an app crash, go to

more_horiz

More

settings

Settings

code

AdvancedDump crash logs

To get device logs if the app is not behaving as expected, record device logs using a Logcat Reader (opens new window).

SergeyIvankov

0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

1

15.10.2017, 16:59. Показов 3389. Ответов 6

Метки нет (Все метки)


Добрый день, подключаю к C# базу Postgresql делаю добавление полей выводит ошибку: «23502: null value in column «IdDepartment» violates not-null constraint»

Мой код:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
 
namespace Kyrsss
{
    public partial class Form1 : Form
    {
        NpgsqlConnection con = new NpgsqlConnection ("Server=localhost;Port=5432;" +
        "User Id=postgres;Password=1qaz;Database=Dean's Office;");
        NpgsqlCommand cmd;
        NpgsqlDataAdapter adapt;
        int iddepartment = 0;
        public Form1()
        {
            InitializeComponent();
            DisplayData();
        }
 
        private void DisplayData()
        {
            con.Open();
            DataTable dt = new DataTable();
            adapt = new NpgsqlDataAdapter("select * from Departments", con);
            adapt.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
        //Clear Data  
        private void ClearData()
        {
            textBox1.Text = "";
            textBox2.Text = "";
            iddepartment = 0;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "" && textBox2.Text != "")
            {
                cmd = new NpgsqlCommand("insert into Departments(titledepartment,phonedepartment) values(@title,@phone)", con);
                con.Open();
                cmd.Parameters.AddWithValue("@title", textBox1.Text);
                cmd.Parameters.AddWithValue("@phone", textBox2.Text);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Inserted Successfully");
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Provide Details!");
            }
        }
 
        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
 
            iddepartment = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
            textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        }
    }
}

Скриншот прикрепил, подскажите пожалуйста в чем собственно проблема.

Миниатюры

Ошибка: null value in column
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

15.10.2017, 16:59

6

359 / 286 / 76

Регистрация: 21.06.2016

Сообщений: 1,115

15.10.2017, 17:05

2

Ну правильно оно всё выводит. Нечего налы сунуть туда где их быть не должно, разбирайтесь с таблицей своей в БД, налы в поле запрещены, а Вы ничего туда не передаёте.



0



0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

15.10.2017, 17:07

 [ТС]

3

Цитата
Сообщение от hoolygan
Посмотреть сообщение

Ну правильно оно всё выводит. Нечего налы сунуть туда где их быть не должно, разбирайтесь с таблицей своей в БД, налы в поле запрещены, а Вы ничего туда не передаёте.

Глянь пожалуйста, вот описание таблицы в БД.

Миниатюры

Ошибка: null value in column
 



0



0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

15.10.2017, 17:39

 [ТС]

4

Так, что нужно сделать, подскажите пожалуйста. Поменять каждому ID тип serial ?



0



1274 / 979 / 137

Регистрация: 01.10.2009

Сообщений: 3,100

Записей в блоге: 1

15.10.2017, 19:56

5

SergeyIvankov, iddepartment null, хотя стоит как not null, и вообще по мне так оно должно быть автоинкрементное, что у Вас скорее всего не сделано



0



0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

15.10.2017, 20:06

 [ТС]

6

Цитата
Сообщение от XIST
Посмотреть сообщение

SergeyIvankov, iddepartment null, хотя стоит как not null, и вообще по мне так оно должно быть автоинкрементное, что у Вас скорее всего не сделано

Сори за глупые вопросы, автоинкрементов нет, тип для первичных ключей брал интеджер. А not null бд выставляло автоматически после того как указывал, что это первичных ключ.
Решением будет изменить всем Idшникам тип данных ?



0



359 / 286 / 76

Регистрация: 21.06.2016

Сообщений: 1,115

15.10.2017, 21:20

7

Ааааа. Это аут.
SergeyIvankov, а ну ка вспоминаем, что такое primary key? И когда вспомним (или хоть раз откроем учебник по БД) попробуем понять, могут ли быть там наловые значения?
Естественно, что программа ругается, ей больше ничего не остается.
В общем, если не хотите отдавать поддержку этой колонки на субд, то будьте добры, указывать значение собственноручно в шарпе ( что не рекомендую для интового поля). Уж лучше тогда guid вписывайте, чтобы не ошибиться с уникальностью.



0



I’m using the following query:

INSERT INTO role (name, created) VALUES ('Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

However, I’m not specifying the primary key (which is id). So my questions is, why is sql server coming back with this error:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'id', table 'CMT_DEV.dbo.role'; column does not allow nulls. INSERT fails.
The statement has been terminated.

James Drinkard's user avatar

asked Apr 4, 2012 at 14:33

Ben's user avatar

0

I’m assuming that id is supposed to be an incrementing value.

You need to set this, or else if you have a non-nullable column, with no default value, if you provide no value it will error.

To set up auto-increment in SQL Server Management Studio:

  • Open your table in Design
  • Select your column and go to Column Properties
  • Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1

answered Apr 4, 2012 at 14:36

Curtis's user avatar

CurtisCurtis

100k65 gold badges267 silver badges349 bronze badges

3

use IDENTITY(1,1) while creating the table
eg

CREATE TABLE SAMPLE(
[Id]     [int]  IDENTITY(1,1) NOT NULL,
[Status] [smallint] NOT NULL,

CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)
)

Nick's user avatar

Nick

1,1583 gold badges26 silver badges35 bronze badges

answered Jan 9, 2018 at 19:41

Minakshi Korad's user avatar

If the id column has no default value, but has NOT NULL constraint, then you have to provide a value yourself

INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

answered Apr 4, 2012 at 14:40

Andy Irving's user avatar

Andy IrvingAndy Irving

2,6371 gold badge14 silver badges11 bronze badges

Encountered the same issue. This is something to do with your table creation. When you created table you have not indicate ‘ID‘ column to be Auto Increment hence you get this error. By making the column Primary Key it cannot be null or contain duplicates hence without Auto Increment pretty obvious to throw column does not allow nulls. INSERT fails.

There are two ways you could fix this issue.

1). via MS SQL Server Management Studio

  1. Got to MS SQL Server Management Studio

  2. Locate your table and right click and select Design

  3. Locate your column and go to Column Properties

  4. Under Indentity Specification: set (Is Identity)=Yes and Indentity
    Increment=1

2). via ALTER SQLs

ALTER TABLE table DROP COLUMN id; // drop the existing ID
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

answered Dec 15, 2022 at 7:02

Du-Lacoste's user avatar

Du-LacosteDu-Lacoste

10.7k2 gold badges64 silver badges50 bronze badges

You either need to specify an ID in the insert, or you need to configure the id column in the database to have Identity Specification = Yes.

answered Apr 4, 2012 at 14:38

JupiterP5's user avatar

JupiterP5JupiterP5

3081 silver badge10 bronze badges

As id is PK it MUST be unique and not null.
If you do not mention any field in the fields list for insert it’ll be supposed to be null or default value.
Set identity (i.e. autoincrement) for this field if you do not want to set it manualy every time.

answered Apr 4, 2012 at 14:38

quzary's user avatar

quzaryquzary

2851 silver badge4 bronze badges

You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.

answered Apr 4, 2012 at 14:44

RisingDragon's user avatar

you didn’t give a value for id. Try this :

INSERT INTO role (id, name, created) VALUES ('example1','Content Coordinator', GETDATE()), ('example2', 'Content Viewer', GETDATE())

Or you can set the auto increment on id field, if you need the id value added automatically.

answered May 9, 2017 at 2:04

natadecoco's user avatar

I had a similar problem and upon looking into it, it was simply a field in the actual table missing id (id was empty/null) — meaning when you try to make the id field the primary key it will result in error because the table contains a row with null value for the primary key.

This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.

answered Nov 1, 2019 at 15:22

vid.dev's user avatar

WARNING! Make sure the target table is locked when using this method
(As per @OnurOmer’s comment)

if you can’t or don’t want to set the autoincrement property of the id, you can set value for the id for each row like this:

INSERT INTO role (id, name, created)
SELECT 
      (select max(id) from role) + ROW_NUMBER() OVER (ORDER BY name)
    , name
    , created
FROM (
    VALUES 
      ('Content Coordinator', GETDATE())
    , ('Content Viewer', GETDATE())
) AS x(name, created)

answered Apr 16, 2018 at 2:13

robotik's user avatar

robotikrobotik

1,7741 gold badge19 silver badges24 bronze badges

2

RULE: You cannot IGNORE those colums that do not allow null values, when inserting new data.

Your Case

  • You’re trying to insert values, while ignoring the id column, which does not allow nulls. Obviously this won’t work.
  • Gladly for you the «Identity Specification» seems to automatically fill the not nullable id values for you (see selected answer), when you later execute the insert query.

My Case

  • The problem (while using SSMS): I was having this error when trying to add a new non-nullable column to an already existing table with data. The error I’d got was:

Cannot insert the value NULL into column ‘id_foreign’, table ‘MyDataBase.dbo.Tmp_ThisTable’; column does not allow nulls. INSERT fails.
The statement has been terminated.

  • The solution:
    1. I created the column I needed id_foreign, allowing nulls.
    2. I edited/inserted all the required values for id_foreign.
    3. Once the values where in place, I went back and unchecked the «Allow Nulls» checkbox. Now the error was gone.

answered Jul 26, 2022 at 14:54

carloswm85's user avatar

carloswm85carloswm85

1,06410 silver badges20 bronze badges

I’m using the following query:

INSERT INTO role (name, created) VALUES ('Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

However, I’m not specifying the primary key (which is id). So my questions is, why is sql server coming back with this error:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'id', table 'CMT_DEV.dbo.role'; column does not allow nulls. INSERT fails.
The statement has been terminated.

James Drinkard's user avatar

asked Apr 4, 2012 at 14:33

Ben's user avatar

0

I’m assuming that id is supposed to be an incrementing value.

You need to set this, or else if you have a non-nullable column, with no default value, if you provide no value it will error.

To set up auto-increment in SQL Server Management Studio:

  • Open your table in Design
  • Select your column and go to Column Properties
  • Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1

answered Apr 4, 2012 at 14:36

Curtis's user avatar

CurtisCurtis

100k65 gold badges267 silver badges349 bronze badges

3

use IDENTITY(1,1) while creating the table
eg

CREATE TABLE SAMPLE(
[Id]     [int]  IDENTITY(1,1) NOT NULL,
[Status] [smallint] NOT NULL,

CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)
)

Nick's user avatar

Nick

1,1583 gold badges26 silver badges35 bronze badges

answered Jan 9, 2018 at 19:41

Minakshi Korad's user avatar

If the id column has no default value, but has NOT NULL constraint, then you have to provide a value yourself

INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

answered Apr 4, 2012 at 14:40

Andy Irving's user avatar

Andy IrvingAndy Irving

2,6371 gold badge14 silver badges11 bronze badges

Encountered the same issue. This is something to do with your table creation. When you created table you have not indicate ‘ID‘ column to be Auto Increment hence you get this error. By making the column Primary Key it cannot be null or contain duplicates hence without Auto Increment pretty obvious to throw column does not allow nulls. INSERT fails.

There are two ways you could fix this issue.

1). via MS SQL Server Management Studio

  1. Got to MS SQL Server Management Studio

  2. Locate your table and right click and select Design

  3. Locate your column and go to Column Properties

  4. Under Indentity Specification: set (Is Identity)=Yes and Indentity
    Increment=1

2). via ALTER SQLs

ALTER TABLE table DROP COLUMN id; // drop the existing ID
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

answered Dec 15, 2022 at 7:02

Du-Lacoste's user avatar

Du-LacosteDu-Lacoste

10.7k2 gold badges64 silver badges50 bronze badges

You either need to specify an ID in the insert, or you need to configure the id column in the database to have Identity Specification = Yes.

answered Apr 4, 2012 at 14:38

JupiterP5's user avatar

JupiterP5JupiterP5

3081 silver badge10 bronze badges

As id is PK it MUST be unique and not null.
If you do not mention any field in the fields list for insert it’ll be supposed to be null or default value.
Set identity (i.e. autoincrement) for this field if you do not want to set it manualy every time.

answered Apr 4, 2012 at 14:38

quzary's user avatar

quzaryquzary

2851 silver badge4 bronze badges

You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.

answered Apr 4, 2012 at 14:44

RisingDragon's user avatar

you didn’t give a value for id. Try this :

INSERT INTO role (id, name, created) VALUES ('example1','Content Coordinator', GETDATE()), ('example2', 'Content Viewer', GETDATE())

Or you can set the auto increment on id field, if you need the id value added automatically.

answered May 9, 2017 at 2:04

natadecoco's user avatar

I had a similar problem and upon looking into it, it was simply a field in the actual table missing id (id was empty/null) — meaning when you try to make the id field the primary key it will result in error because the table contains a row with null value for the primary key.

This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.

answered Nov 1, 2019 at 15:22

vid.dev's user avatar

WARNING! Make sure the target table is locked when using this method
(As per @OnurOmer’s comment)

if you can’t or don’t want to set the autoincrement property of the id, you can set value for the id for each row like this:

INSERT INTO role (id, name, created)
SELECT 
      (select max(id) from role) + ROW_NUMBER() OVER (ORDER BY name)
    , name
    , created
FROM (
    VALUES 
      ('Content Coordinator', GETDATE())
    , ('Content Viewer', GETDATE())
) AS x(name, created)

answered Apr 16, 2018 at 2:13

robotik's user avatar

robotikrobotik

1,7741 gold badge19 silver badges24 bronze badges

2

RULE: You cannot IGNORE those colums that do not allow null values, when inserting new data.

Your Case

  • You’re trying to insert values, while ignoring the id column, which does not allow nulls. Obviously this won’t work.
  • Gladly for you the «Identity Specification» seems to automatically fill the not nullable id values for you (see selected answer), when you later execute the insert query.

My Case

  • The problem (while using SSMS): I was having this error when trying to add a new non-nullable column to an already existing table with data. The error I’d got was:

Cannot insert the value NULL into column ‘id_foreign’, table ‘MyDataBase.dbo.Tmp_ThisTable’; column does not allow nulls. INSERT fails.
The statement has been terminated.

  • The solution:
    1. I created the column I needed id_foreign, allowing nulls.
    2. I edited/inserted all the required values for id_foreign.
    3. Once the values where in place, I went back and unchecked the «Allow Nulls» checkbox. Now the error was gone.

answered Jul 26, 2022 at 14:54

carloswm85's user avatar

carloswm85carloswm85

1,06410 silver badges20 bronze badges

Понравилась статья? Поделить с друзьями:
  • Display inf ошибка
  • Display help exe ошибка
  • Display error box
  • Display acceleration disabled after effects как исправить
  • Dispenser count error