sql:如何为每个添加的新行增加一个id?

时间:2018-08-24 06:23:24

标签: python sql

我想为添加到我的sql数据库的每个新行提供一个ID(唯一),而无需明确询问用户。我正在考虑使用bigint并增加与上一行ID相比增加的每一行的值。

示例:

name   id
xyz     1

现在将另一个数据添加到该表中,例如name ='abc',我希望ID自动增加为2,然后保存所有类似的图片

name   id
xyz     1
abc     2

有什么办法可以做到?还是任何其他可以随每一行增加的数据类型?

P.S。我在python上使用sql,因此我可以访问最后一行,然后通过fetchall()查询向其添加1,但这似乎并不是有效的方法。

2 个答案:

答案 0 :(得分:0)

您尝试使用sql中的身份。自动递增且唯一 https://www.w3schools.com/sql/sql_autoincrement.asp

查询:-

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-d68919405364> in <module>()
----> 1 df.iplot(kind='scatter',x='A',y='B',mode='markers',size=10)

C:\ProgramData\Anaconda3\lib\site-packages\cufflinks\plotlytools.py in _iplot(self, kind, data, layout, filename, sharing, title, xTitle, yTitle, zTitle, theme, colors, colorscale, fill, width, dash, mode, interpolation, symbol, size, barmode, sortbars, bargap, bargroupgap, bins, histnorm, histfunc, orientation, boxpoints, annotations, keys, bestfit, bestfit_colors, mean, mean_colors, categories, x, y, z, text, gridcolor, zerolinecolor, margin, labels, values, secondary_y, secondary_y_title, subplots, shape, error_x, error_y, error_type, locations, lon, lat, asFrame, asDates, asFigure, asImage, dimensions, asPlot, asUrl, online, **kwargs)
    761                                                                 bargap=bargap,bargroupgap=bargroupgap,annotations=annotations,gridcolor=gridcolor,
    762                                                            dimensions=dimensions,
--> 763                               zerolinecolor=zerolinecolor,margin=margin,is3d='3d' in kind,**l_kwargs)
    764 
    765         if not data:

C:\ProgramData\Anaconda3\lib\site-packages\cufflinks\tools.py in getLayout(kind, theme, title, xTitle, yTitle, zTitle, barmode, bargap, bargroupgap, margin, dimensions, width, height, annotations, is3d, **kwargs)
    199 
    200         theme_data = getTheme(theme)
--> 201         layout=go.Layout(theme_data['layout'])
    202         layout['xaxis1'].update({'title':xTitle})
    203         layout['yaxis1'].update({'title':yTitle})

C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\_layout.py in __init__(self, arg, angularaxis, annotations, autosize, bargap, bargroupgap, barmode, barnorm, boxgap, boxgroupgap, boxmode, calendar, colorway, datarevision, direction, dragmode, font, geo, grid, height, hiddenlabels, hiddenlabelssrc, hidesources, hoverdistance, hoverlabel, hovermode, images, legend, mapbox, margin, orientation, paper_bgcolor, plot_bgcolor, polar, radialaxis, scene, selectdirection, separators, shapes, showlegend, sliders, spikedistance, template, ternary, title, titlefont, updatemenus, violingap, violingroupgap, violinmode, width, xaxis, yaxis, **kwargs)
   3735         self.images = images if images is not None else _v
   3736         _v = arg.pop('legend', None)
-> 3737         self.legend = legend if legend is not None else _v
   3738         _v = arg.pop('mapbox', None)
   3739         self.mapbox = mapbox if mapbox is not None else _v

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value)
   3601         if match is None:
   3602             # Set as ordinary property
-> 3603             super(BaseLayoutHierarchyType, self).__setattr__(prop, value)
   3604         else:
   3605             # Set as subplotid property

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value)
   2702                 prop in self._validators):
   2703             # Let known properties and private properties through
-> 2704             super(BasePlotlyType, self).__setattr__(prop, value)
   2705         else:
   2706             # Raise error on unknown public properties

C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\_layout.py in legend(self, val)
   1224     @legend.setter
   1225     def legend(self, val):
-> 1226         self['legend'] = val
   1227 
   1228     # mapbox

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value)
   3587         if match is None:
   3588             # Set as ordinary property
-> 3589             super(BaseLayoutHierarchyType, self).__setitem__(prop, value)
   3590         else:
   3591             # Set as subplotid property

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value)
   2665             # ### Handle compound property ###
   2666             if isinstance(validator, CompoundValidator):
-> 2667                 self._set_compound_prop(prop, value)
   2668 
   2669             # ### Handle compound array property ###

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_compound_prop(self, prop, val)
   2963         validator = self._validators.get(prop)
   2964         # type: BasePlotlyType
-> 2965         val = validator.validate_coerce(val)
   2966 
   2967         # Save deep copies of current and new states

C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v)
   1790 
   1791         elif isinstance(v, dict):
-> 1792             v = self.data_class(**v)
   1793 
   1794         elif isinstance(v, self.data_class):

C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\layout\_legend.py in __init__(self, arg, bgcolor, bordercolor, borderwidth, font, orientation, tracegroupgap, traceorder, x, xanchor, y, yanchor, **kwargs)
    500         # ----------------------------------
    501         _v = arg.pop('bgcolor', None)
--> 502         self.bgcolor = bgcolor if bgcolor is not None else _v
    503         _v = arg.pop('bordercolor', None)
    504         self.bordercolor = bordercolor if bordercolor is not None else _v

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value)
   2702                 prop in self._validators):
   2703             # Let known properties and private properties through
-> 2704             super(BasePlotlyType, self).__setattr__(prop, value)
   2705         else:
   2706             # Raise error on unknown public properties

C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\layout\_legend.py in bgcolor(self, val)
     62     @bgcolor.setter
     63     def bgcolor(self, val):
---> 64         self['bgcolor'] = val
     65 
     66     # bordercolor

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value)
   2674             # ### Handle simple property ###
   2675             else:
-> 2676                 self._set_prop(prop, value)
   2677 
   2678         # Handle non-scalar case

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_prop(self, prop, val)
   2904         # ------------
   2905         validator = self._validators.get(prop)
-> 2906         val = validator.validate_coerce(val)
   2907 
   2908         # val is None

C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v, should_raise)
   1068             validated_v = self.vc_scalar(v)
   1069             if validated_v is None and should_raise:
-> 1070                 self.raise_invalid_val(v)
   1071 
   1072             v = validated_v

C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in raise_invalid_val(self, v)
    214             typ=type_str(v),
    215             v=repr(v),
--> 216             valid_clr_desc=self.description()))
    217 
    218     def raise_invalid_elements(self, invalid_els):

ValueError: 
    Invalid value of type 'builtins.str' received for the 'bgcolor' property of layout.legend
        Received value: 'pearl02'

    The 'bgcolor' property is a color and may be specified as:
      - A hex string (e.g. '#ff0000')
      - An rgb/rgba string (e.g. 'rgb(255,0,0)')
      - An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
      - An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
      - A named CSS color:
            aliceblue, antiquewhite, aqua, aquamarine, azure,
            beige, bisque, black, blanchedalmond, blue,
            blueviolet, brown, burlywood, cadetblue,
            chartreuse, chocolate, coral, cornflowerblue,
            cornsilk, crimson, cyan, darkblue, darkcyan,
            darkgoldenrod, darkgray, darkgrey, darkgreen,
            darkkhaki, darkmagenta, darkolivegreen, darkorange,
            darkorchid, darkred, darksalmon, darkseagreen,
            darkslateblue, darkslategray, darkslategrey,
            darkturquoise, darkviolet, deeppink, deepskyblue,
            dimgray, dimgrey, dodgerblue, firebrick,
            floralwhite, forestgreen, fuchsia, gainsboro,
            ghostwhite, gold, goldenrod, gray, grey, green,
            greenyellow, honeydew, hotpink, indianred, indigo,
            ivory, khaki, lavender, lavenderblush, lawngreen,
            lemonchiffon, lightblue, lightcoral, lightcyan,
            lightgoldenrodyellow, lightgray, lightgrey,
            lightgreen, lightpink, lightsalmon, lightseagreen,
            lightskyblue, lightslategray, lightslategrey,
            lightsteelblue, lightyellow, lime, limegreen,
            linen, magenta, maroon, mediumaquamarine,
            mediumblue, mediumorchid, mediumpurple,
            mediumseagreen, mediumslateblue, mediumspringgreen,
            mediumturquoise, mediumvioletred, midnightblue,
            mintcream, mistyrose, moccasin, navajowhite, navy,
            oldlace, olive, olivedrab, orange, orangered,
            orchid, palegoldenrod, palegreen, paleturquoise,
            palevioletred, papayawhip, peachpuff, peru, pink,
            plum, powderblue, purple, red, rosybrown,
            royalblue, saddlebrown, salmon, sandybrown,
            seagreen, seashell, sienna, silver, skyblue,
            slateblue, slategray, slategrey, snow, springgreen,
            steelblue, tan, teal, thistle, tomato, turquoise,
            violet, wheat, white, whitesmoke, yellow,
            yellowgreen

如果已经存在表

CREATE TABLE Persons (
  ID int NOT NULL AUTO_INCREMENT,
  LastName varchar(255) NOT NULL,
  FirstName varchar(255),
  Age int,
  PRIMARY KEY (ID)
);

答案 1 :(得分:0)

在表格中保留列名ID,例如

ID int NOT NULL AUTO_INCREMENT;

然后使用此方法

previousid=SELECT LAST_INSERT_ID();
primarykey=PK('cu',previousid);
print primarykey; //this will print a key like CU-18-000005

function PK(keycode,last_id)
{
    seq=str_pad(last_id, 6, "0", STR_PAD_LEFT);
    return strtoupper(keycode).'-'.date('y').'-'.seq;
}