我有以下查询
string sql =
"IF NOT EXISTS(SELECT testId from TestData where testId=@testId) " +
"Insert INTO TestData (testId, jsonString) VALUES(@testId, @jsonstring) " +
"else " +
"UPDATE TestData SET jsonString=@jsonstring WHERE testId=@testId " +
"SELECT CAST(scope_identity() AS int)";
为了使TestData
表中的一行(如果不存在则创建)或者更新(如果不存在)。
我第一次使用它时,所以当记录不存在时,它可以正常工作。如果我再次调用该函数:
conn.Open();
newID = (Int32)cmd.ExecuteScalar();
所以这次记录已经存在,我在尝试转换为Int32
时可能会出现转换错误。
我的查询是否有问题,我该怎么做才能解决这个问题?
答案 0 :(得分:1)
错误可能是因为你已经有了testid.scope_identity()将返回null,因为它做了任何身份操作。 使用 选择@testId进行更新。
答案 1 :(得分:1)
据推测,您需要更像这样的代码:
import pygame
# --- constants ---
BLACK = ( 0, 0, 0)
RED = (255, 0, 0)
# --- classes ---
class Label():
def __init__(self, text, x, y, width):
font = pygame.font.SysFont(None, 35)
# generate full image
self.image = font.render(text, True, RED)
self.rect = self.image.get_rect(x=x, y=y)
self.width = width
self.speed = 1
# offset of visible part
self.offset_x = 0
self.max_offset_x = self.rect.width - self.width
# visible part of image as 'rect' - 'width' is always the same
self.sub_image_rect = self.image.get_rect(x=0, width=self.width) # changed
def move(self):
# change offset
self.offset_x += self.speed
# change move direction
if self.offset_x < 0:
self.offset_x = 0
self.speed = -self.speed
elif self.offset_x > self.max_offset_x:
self.offset_x = self.max_offset_x
self.speed = -self.speed
# visible part of image - change only `x`
self.sub_image_rect.x = self.offset_x # changed
def draw(self, surface):
surface.blit(self.image, self.rect, area=self.sub_image_rect) # changed
# --- main ---
pygame.init()
screen = pygame.display.set_mode((800,600))
label = Label("Hello World of Python and Pygame!", 100, 100, 200)
# --- mainloop ---
fps = pygame.time.Clock()
running = True
while running:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# --- updates ---
label.move()
# --- draws ---
screen.fill(BLACK)
label.draw(screen)
fps.tick(25)
pygame.display.flip()
# --- the end ---
pygame.quit()
我假设IF NOT EXISTS (SELECT 1 from TestData where testId = @testId)
BEGIN
Insert INTO TestData(testId, jsonString)
VALUES(@testId, @jsonstring);
SELECT CAST(scope_identity() AS int);
END
ELSE
BEGIN
UPDATE TestData SET jsonString = @jsonstring WHERE testId = @testId;
SELECT CAST(id as int) FROM TestData WHERE testId = @testId;
END;
以外的某些列是标识列 - 比如说testId
。通常,您不会在id
语句中设置标识列。
此外,insert
可能适用于您的目的。但是从新行返回信息的最安全方法是使用scope_identity()
子句(请参阅here)。