娇纵

文章 评论 浏览 27

娇纵 2025-02-21 01:26:09

使用changeNotifier时,您需要调用notifyListeners当值更改时。您还需要让小部件收听changeNotifier,以便知道何时重建。

这样做的最常见方法是使用提供者 package,其中包括conseNotifierProviderProviderProviderProviderProviderProvider小部件。

使用提供商,您的代码看起来像这样:

class GlobalSingleton extends ChangeNotifier {
  static final GlobalSingleton _instance = GlobalSingleton._internal();

  // passes the instantiation to the _instance object
  factory GlobalSingleton() {
    return _instance;
  }

  //initialize variables in here
  GlobalSingleton._internal() {
    _cartSize = 0;
  }

  late int _cartSize;

  int get cartSize => _cartSize;

  void set cartSize(int newCartSize) {
    _cartSize = newCartSize;
    notifyListeners();
  }
}

在这里,我们更新您的Singleton,以便每当设置CartSize时,都会调用notifyListeners()

接下来,您需要更新小部件以收听更改:

import 'package:######/globals/globals.dart';
import 'package:flutter/material.dart';

class BuildMarketplaceCartIcon extends StatefulWidget {
  const BuildMarketplaceCartIcon({Key? key}) : super(key: key);

  @override
  State<BuildMarketplaceCartIcon> createState() =>
      _BuildMarketplaceCartIconState();
}

class _BuildMarketplaceCartIconState extends State<BuildMarketplaceCartIcon> {
  CRUDMarketplaceCart localCartData = CRUDMarketplaceCart();

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: 72,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const <Widget>[
                Icon(Icons.shopping_cart),
                Text(
                  'Cart',
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 6,
                  vertical: 2,
                ),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                alignment: Alignment.center,
                child: ChangeNotifierProvider.value(
                  value: GlobalSingleton(),
                  child: Consumer<GlobalSingleton>(
                    builder: (context, singleton, child) {
                      return Text(
                        '${singleton.cartSize}',
                      );
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

在这里,我将提供商窗口小部件直接封闭consumer widget-但是,如果您需要Singleton的值在一个以上的位置,您可以将提供商更高的位置放在小部件树上,以便它是任何consumper的共同祖先,它会听取Singleton中的更改。

When using ChangeNotifier you need to call notifyListeners when the value changes. You also need to have your widget listen to the ChangeNotifier, so that it knows when to rebuild.

The most common way to go about that is to use the provider package, which includes the ChangeNotifierProvider widget.

Using provider, your code would look something like this:

class GlobalSingleton extends ChangeNotifier {
  static final GlobalSingleton _instance = GlobalSingleton._internal();

  // passes the instantiation to the _instance object
  factory GlobalSingleton() {
    return _instance;
  }

  //initialize variables in here
  GlobalSingleton._internal() {
    _cartSize = 0;
  }

  late int _cartSize;

  int get cartSize => _cartSize;

  void set cartSize(int newCartSize) {
    _cartSize = newCartSize;
    notifyListeners();
  }
}

Here, we update your singleton so that it will call notifyListeners() whenever the cartSize is set.

Next you'll need to update your widget to listen to the changes:

import 'package:######/globals/globals.dart';
import 'package:flutter/material.dart';

class BuildMarketplaceCartIcon extends StatefulWidget {
  const BuildMarketplaceCartIcon({Key? key}) : super(key: key);

  @override
  State<BuildMarketplaceCartIcon> createState() =>
      _BuildMarketplaceCartIconState();
}

class _BuildMarketplaceCartIconState extends State<BuildMarketplaceCartIcon> {
  CRUDMarketplaceCart localCartData = CRUDMarketplaceCart();

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: 72,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const <Widget>[
                Icon(Icons.shopping_cart),
                Text(
                  'Cart',
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 6,
                  vertical: 2,
                ),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                alignment: Alignment.center,
                child: ChangeNotifierProvider.value(
                  value: GlobalSingleton(),
                  child: Consumer<GlobalSingleton>(
                    builder: (context, singleton, child) {
                      return Text(
                        '${singleton.cartSize}',
                      );
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Here I put the Provider widget as directly enclosing the Consumer widget - however, if you need the singleton's value in more than one place, you can put the Provider higher up the widget tree so that it's a common ancestor of any Consumer that listens to changes in the singleton.

如何重建Singleton Value Change的颤音小部件

娇纵 2025-02-20 10:52:37

您需要做的就是在src/文件夹中复制所有代码。然后,您应该仅在主机和Docker映像之间安装该文件夹(IE src/)。这样,您只需要在添加新软件包时重建docker-compose文件。

  #EET service
  eetapi:
    container_name: eetapi_container
    build: .
    volumes:
      - ./src/:/usr/src/app/src/
    ports:
      - "3000:3000"
    ...

All you need to do is copy all your code inside a src/ folder. Then you should mount only that folder (i.e. src/) between the host and the docker image. That way, you will only need to rebuild your docker-compose file when you add a new package to package.json.

  #EET service
  eetapi:
    container_name: eetapi_container
    build: .
    volumes:
      - ./src/:/usr/src/app/src/
    ports:
      - "3000:3000"
    ...

Docker失败-BCRYPT_LIB.NODE:EXEC格式错误

娇纵 2025-02-20 10:36:35

尝试添加此内容:(

<script>const pagecode = document.documentElement.innerHtml;</script>    
    
<button onclick="document.documentElement.innerHtml = ''; document.documentElement.innerHtml = pagecode; startGame()">Restart</button>

不错的游戏!

Try to add this:

<script>const pagecode = document.documentElement.innerHtml;</script>    
    
<button onclick="document.documentElement.innerHtml = ''; document.documentElement.innerHtml = pagecode; startGame()">Restart</button>

(Nice game! ????)

如何在HTML JavaScript Flappy Bird Type游戏中添加重新启动按钮?

娇纵 2025-02-20 07:45:59

提供自己的ServiceProvider的问题

services.AddDbContext<ApplicationDbContext>(
    options => options
        .UseInternalServiceProvider(services
            .AddEntityFrameworkNpgsql()
            .AddEntityFrameworkProxies()
            .AddScoped<IHistoryRepository, CustomHistoryRepository>()
            .BuildServiceProvider())
        .UseLazyLoadingProxies()
        .EnableSensitiveDataLogging(enableSensitiveDataLogging));

这似乎解决了以最小输入 > AddentityFrameworknpgsql()是PostgreSQL的NPGSQL提供程序的特定于。

This seems to solve the problem of providing your own ServiceProvider with minimal input and thus, in turn, exposing all services, including IConfiguration, to CustomHistoryProvider:

services.AddDbContext<ApplicationDbContext>(
    options => options
        .UseInternalServiceProvider(services
            .AddEntityFrameworkNpgsql()
            .AddEntityFrameworkProxies()
            .AddScoped<IHistoryRepository, CustomHistoryRepository>()
            .BuildServiceProvider())
        .UseLazyLoadingProxies()
        .EnableSensitiveDataLogging(enableSensitiveDataLogging));

Note that use of AddEntityFrameworkNpgsql() is specific to Npgsql provider for PostgreSQL.

将服务传递给自定义的《文化历史实施》

娇纵 2025-02-19 21:36:47

尝试在遍历变量时,尝试删除额外的空间,send_email()get_news函数:

f1 = ""
for i in new:
  f1 += str(i) + "" #Extra space removed from + " " to + ""
new = f1

Try removing the extra space when traversing new variable, inside send_email() and get_news functions:

f1 = ""
for i in new:
  f1 += str(i) + "" #Extra space removed from + " " to + ""
new = f1

你好呀!我在与Python发送电子邮件时有问题。 (Yagmail)

娇纵 2025-02-19 04:43:08

我相信,除了使用data-cy =“ add-unique-id-here”选择器之外,尝试选择其他任何元素违反了赛普拉斯的最佳实践。这些文档建议使用CSS风格的选择器很脆弱,并且在您更新代码时可能会导致测试失败。通过使用数据 - *选择器,您可以始终选择所需的东西。

这是柏树文档的链接: https://docs.cypress。 io/guides/co点/最佳练习#选择元素

在您的情况下,添加
&lt; span class =“ ui-lib-checkbox __box” data-cy =“ Dexciptive-checkbox-name”&gt; &lt; svg&gt; ...&lt;/svg&gt; &lt;/span&gt; to html

cy.get('[data-cy = Decumbitive-checkbox-name]') to cypress测试文件,应该解决问题。

I believe it goes against cypress' best practices to try and select any element other than using data-cy="add-unique-id-here" selector. The docs suggest that using CSS-style selectors is brittle, and may cause tests to fail in the future when you update your code. By using data-* selectors, you can gaurantee you're always selecting what you need.

Here's the link for the cypress docs: https://docs.cypress.io/guides/references/best-practices#Selecting-Elements

Example code from cypress docs

In your case, adding
<span class="ui-lib-checkbox__box" data-cy="descriptive-checkbox-name"> <svg>...</svg> </span> to your html

and cy.get('[data-cy=descriptive-checkbox-name]') to your cypress testing file, should do the trick.

赛普拉斯如何勾选没有唯一选择器的复选框

娇纵 2025-02-18 23:45:36

没有区别。

    def joinpath(self, *args):
        """Combine this path with one or several arguments, and return a
        new path representing either a subpath (if all arguments are relative
        paths) or a totally different path (if one of the arguments is
        anchored).
        """
        return self._make_child(args)

    def __truediv__(self, key):
        try:
            return self._make_child((key,))
        except TypeError:
            return NotImplemented

”将多个参数传递到joinpath eg a.joinpath(b,c,d)/ < / code>的等效词是a / b / c / d < / code>。

There is no difference. The source code confirms this:

    def joinpath(self, *args):
        """Combine this path with one or several arguments, and return a
        new path representing either a subpath (if all arguments are relative
        paths) or a totally different path (if one of the arguments is
        anchored).
        """
        return self._make_child(args)

    def __truediv__(self, key):
        try:
            return self._make_child((key,))
        except TypeError:
            return NotImplemented

Note you can pass multiple arguments to joinpath e.g. a.joinpath(b, c, d). The equivalent for / would be a / b / c / d.

“加入Path”之间的区别和“/&quot”在Pathlib中

娇纵 2025-02-18 04:55:54

单击一个选项卡后,将弹出一个窗口以确认?

After clicking the a tab, a window will pop up to confirm?

如何致电Sweet Alert 2对PHP Echo链接的确认?

娇纵 2025-02-17 23:52:20

我面临同一问题,但是与您不同,因为我有几个通用控制器,其中响应类型基于通用参数而有所不同。解决方案是不要即时生成架构,并将其明确分配给结果。而是获取或生成架构并将其设置为参考。

例如:

var dtoType = typeof(FooDto);
var okResponse = new OpenApiResponse
{
    Schema = new JsonSchema()
    {
        Reference = GetSchemaForType(context, dtoType)
    }
};
context.OperationDescription.Operation.Responses.Add(StatusCodes.Status200OK.ToString(), okResponse);

在使用此方法获取或生成模式的同时:

private static JsonSchema GetSchemaForType(OperationProcessorContext context, Type type)
{
    var schema = !context.SchemaResolver.HasSchema(type, false)
        ? context.SchemaGenerator.Generate(type, context.SchemaResolver)
        : context.SchemaResolver.GetSchema(type, false);

    return schema;
}

如果您查看上面发布的JSON,则发现该模式不包括响应架构本身,而是对其进行引用。操作描述是最终被序列化的对象,因此您可以查看有效的Swagger.json,以获取有关如何在代码中正确修改它的参考。

顺便说一句:同样适用于数组类型。我也有问题为他们找到适当的解决方案,因此,如果您需要它,这也许可以帮助您。

var dtoType = typeof(FooDto);

var dtoSchema = GetSchemaForType(context, dtoType);
var okResponse = new OpenApiResponse
{
    Schema = new JsonSchema()
    {
        Type = JsonObjectType.Array,
        Item = new JsonSchema()
        {
            Reference = dtoSchema
        }
    }
};
operation.Responses.Add(StatusCodes.Status200OK.ToString(), okResponse);

I was facing the same issue, but unlike you because I am having a couple of generic controllers where the response type differs based on generic parameters. The solution is to not generate a schema on the fly and plainly assigning it to the result. Rather, get or generate the schema and set it as a reference.

As an example:

var dtoType = typeof(FooDto);
var okResponse = new OpenApiResponse
{
    Schema = new JsonSchema()
    {
        Reference = GetSchemaForType(context, dtoType)
    }
};
context.OperationDescription.Operation.Responses.Add(StatusCodes.Status200OK.ToString(), okResponse);

while using this method to get or generate the schema:

private static JsonSchema GetSchemaForType(OperationProcessorContext context, Type type)
{
    var schema = !context.SchemaResolver.HasSchema(type, false)
        ? context.SchemaGenerator.Generate(type, context.SchemaResolver)
        : context.SchemaResolver.GetSchema(type, false);

    return schema;
}

If you look at the json you posted above you see that the schema does not include the response schema itself but a reference to it. The OperationDescription is the object that ends up being serialized so you can look at a valid swagger.json to get a reference on how to properly modify it in code.

Btw: same applies to array types. I had issues finding a proper solution for them as well so maybe this helps you out in case you need it.

var dtoType = typeof(FooDto);

var dtoSchema = GetSchemaForType(context, dtoType);
var okResponse = new OpenApiResponse
{
    Schema = new JsonSchema()
    {
        Type = JsonObjectType.Array,
        Item = new JsonSchema()
        {
            Reference = dtoSchema
        }
    }
};
operation.Responses.Add(StatusCodes.Status200OK.ToString(), okResponse);

NSWAG-常见操作响应操作处理器

娇纵 2025-02-17 23:09:03

我知道我参加聚会有点迟了,但也许将来会对某人有所帮助。

您可以通过以下方式扩展zod架构:

const Person = zod.object({
    name: z.string().default(''),
    age: z.number().nullable().default(null)
}).default({}); // .default({}) could be omitted in this case but should be set in nested objects

现在,您可以通过致电以下方式检索所需的输出:

const InstancePerson = Person.parse({});

I know that I am a little late to the party but maybe it will help someone in the future.

You could extend your zod schema in the following way:

const Person = zod.object({
    name: z.string().default(''),
    age: z.number().nullable().default(null)
}).default({}); // .default({}) could be omitted in this case but should be set in nested objects

Now, you can retrieve your desired output by calling:

const InstancePerson = Person.parse({});

ZOD:从默认值创建一个原始对象

娇纵 2025-02-17 17:21:53

您可以使用 pathlib.path.home() /代码>为此。

这是一个示例:

from qrcode import QRCode
from pathlib import Path

pictures_folder = Path.home() / 'Pictures'

if pictures_folder.is_dir():
    data = 'https://stackoverflow.com'
    qr = QRCode(version=1)
    qr.add_data(data)
    img = qr.make_image(fill_color='white', back_color='purple')

    img.save(pictures_folder / 'qrcode.png')
else:
    print(f"{pictures_folder} folder doesn't exist!")

上面的摘要是便携式的,将在Python支持的大多数平台上工作。

You can use pathlib.Path.home() for that.

Here is an example:

from qrcode import QRCode
from pathlib import Path

pictures_folder = Path.home() / 'Pictures'

if pictures_folder.is_dir():
    data = 'https://stackoverflow.com'
    qr = QRCode(version=1)
    qr.add_data(data)
    img = qr.make_image(fill_color='white', back_color='purple')

    img.save(pictures_folder / 'qrcode.png')
else:
    print(f"{pictures_folder} folder doesn't exist!")

The snippet above is portable and will work on most platforms supported by Python.

找到操作系统的图片文件夹的CLI

娇纵 2025-02-17 16:04:53

您可以设置sql_select_limit 文档

它定义了最大的行数,将从某些语句返回。

设置SQL_SELECT_LIMIT = 1;

如果选择有限制子句,则限制优先于SQL_SELECT_LIMIT的值。

可以将此参数设置为全局或每个会话。

You can set SQL_SELECT_LIMIT Documentation

It defines maximum number of rows, that will be returned from SELECT statements.

SET SQL_SELECT_LIMIT = 1;

If a SELECT has a LIMIT clause, the LIMIT takes precedence over the value of sql_select_limit.

This parameter can be set global or per session.

如何使MySQL返回特定数量的行或以下的所有选择查询,而无需限制子句?

娇纵 2025-02-17 11:32:50

您需要在网关中添加buildservice函数,该函数将JSON串起网关中的上下文,然后将其注入将发送到子图中的标头,然后在该子图中,您需要分析该标头并自己将其放在上下文中,以便您的决心可以访问它。这样的事情:

{    
  gateway: {
    buildService({ url }) {
      return new RemoteGraphQLDataSource({
        url,
        willSendRequest({ request, context }) {
          request.http.headers.set('X-GQL-Context', JSON.stringify(context))
        },
      })
    },
  },
}

You would need to add a buildService function in your gateway that json stringifies the context in the gateway and then injects that into a header that will be sent to the subgraph and then in the subgraph you will need to parse that header and put that into the context yourself so your resolves can access it. Something like this:

{    
  gateway: {
    buildService({ url }) {
      return new RemoteGraphQLDataSource({
        url,
        willSendRequest({ request, context }) {
          request.http.headers.set('X-GQL-Context', JSON.stringify(context))
        },
      })
    },
  },
}

使用GQLGEN的联合GraphQl上下文

娇纵 2025-02-17 09:25:26

您应该使用@html.dropdownlistfor()但不使用@html.textboxfor()

@Html.DropDownListFor(model => model.ItemId, 
    new SelectList(Model.ListItemId, "Value", "Text" ), 
    new { @class = "form-control"})

在您的控制器中,您会错过text> text属性seletListItem

objItemViewModel.ListItemId = (from objItem in objShopOnlineDBEntities.Items
                               select new SelectListItem()
                               {
                                   Text = "<Item Text>",
                                   Value = objItem.ItemId.ToString(),
                                   Selected = true
                               })
                               .ToList();

You should use @Html.DropDownListFor() but not @Html.TextBoxFor()

@Html.DropDownListFor(model => model.ItemId, 
    new SelectList(Model.ListItemId, "Value", "Text" ), 
    new { @class = "form-control"})

While in your controller, you miss out the Text property for the SeletListItem.

objItemViewModel.ListItemId = (from objItem in objShopOnlineDBEntities.Items
                               select new SelectListItem()
                               {
                                   Text = "<Item Text>",
                                   Value = objItem.ItemId.ToString(),
                                   Selected = true
                               })
                               .ToList();

无法转换为&#x27; web.mvc.SelectList&#x27;到字符串&#x27;所以显示我的物品ID

娇纵 2025-02-17 07:14:56

MySQL中的问题

,某些单词之类的单词选择,insertdelete等是保留单词。由于它们具有特殊的含义,因此每当您将其用作表名称,列名称或其他类型的标识符时,MySQL将其视为语法错误 - 除非您将标识符围绕着标识符。

如官方文档中所述,在 10.2架构对象 < /a>(添加了重点):

MySQL中的某些对象,包括数据库,表,索引,列,别名,视图,存储过程,分区,表空间和其他对象名称被称为 标识符

...

如果标识符包含特殊字符或 保留的单词 ,则每当您参考时,您必须必须引用它。

...

标识符引用字符是 backtick (“ `'):

可以在部分中找到关键字和保留单词的完整列表 10.3关键字和保留单词 。在该页面中,单词后面是“(r)”是保留的单词。下面列出了一些保留的单词,其中包括许多倾向于引起此问题的词。

  • 添加
  • 通过
  • 呼叫
  • 情况
  • 下的情况
  • 删除
  • DESC
  • 中的
  • 间隔
  • 索引
  • 插入
  • 描述
  • 关键
  • 例如
  • 限制
  • 匹配
  • 选项
  • 订单
  • 分区
  • 等级
  • 参考选择
  • 更新
  • 解决
  • 位置

方案

您有两个选项的

。 1。不要将保留的单词作为标识符

最简单的解决方案只是避免使用保留的单词作为标识符。您可能可以为您的列找到另一个合理的名称,而不是一个保留的单词。

这样做有两个优点:

  • 它消除了您或其他使用数据库的开发人员会意外地写出语法错误,因为忘记或不知道 - 特定标识符是保留的单词。 MySQL中有许多保留的单词,大多数开发人员不太可能知道所有这些单词。首先不使用这些单词,您可以避免为自己或将来的开发人员留下陷阱。

  • 引用标识符的手段在SQL方言之间有所不同。虽然MySQL默认使用Backtick来引用标识符,但符合ANSI的SQL(实际上是在ANSI SQL模式下的MySQL,如所指出的 )使用双引号来引用标识符。因此,引用背景标识符的查询不太容易移植到其他SQL方言。


纯粹是为了降低未来错误的风险,这通常是一个明智的行动,而不是回顾标识符。

请使用反向设置

2。如果无法重命名表或列, ,如前列表中所述的backticks()中所述,将有问题的标识符包裹起来。

一个示例来说明用法(取自 10.3个关键字和保留单词):<<<):

< pre> mysql&gt; 创建表间隔(begin int,end int);
错误1064(42000):您的SQL语法有错误。
接近“间隔(开始int,end int)”

mysql&gt; 创建表`interval'(begin int,end int);
查询OK,0行影响(0.01 sec)

同样,可以通过将关键字包装在Backticks中来解决问题的查询,如下所示:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

语法错误是由于使用保留的单词作为MySQL中的表或列名称

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文