问题描述
我正在使用带有sql Server配置文件的Slick。我遇到以下错误:
Exception in thread "main" java.sql.sqlException: Invalid object name 'application.sch.place_table'.
尝试执行TableQuery.result
时(请参见下面的代码中的exec1
)。但是,对于普通的sql不会发生这种情况(请参见下面的代码中的exec2
)。
case class Source(rowId: Long,placeId: Int)
class SourceTable(tag: Tag) extends Table[Source](tag,"application.sch.place_table") {
def rowId = column[Long]("RowID")
def placeId = column[Int]("place_id")
def * = (rowId,placeId).mapTo[Source]
}
object SlickTest extends App {
val db: sqlServerProfile.backend.DatabaseDef =
Database.forURL(
url = "jdbc:jtds:sqlserver://localhost:3000/place_db",user = "user",password = "user123",driver = "slick.jdbc.sqlServerProfile"
)
lazy val sources = TableQuery[SourceTable]
val exec1 = Await.result(
db.run(sources.result),Duration.create(1,TimeUnit.MINUTES)
) // NOT OK
val exec2 = Await.result(
db.run {
sql"""SELECT "RowID","place_id" FROM application.sch.place_table """
.as[(Long,Int)]
},TimeUnit.MINUTES)
) // OK
}
此问题似乎是因为从TableQuery
生成的sql的表名包含双引号,即
println(sources.result.statment.mkString) //select "RowID","place_id" from "application.sch.place_table"
如何解决此问题?
解决方法
经过一番研究和反复试验,结果发现我需要在连接字符串中指定数据库名称并标记架构名称。
因此,从上面的代码中,我需要将其更改为:
ValueError: Dataframe has no rows.
和
# models.py
class Attachment(models.Model):
ticket = models.ForeignKey(Ticket,on_delete=models.CASCADE,related_name='attachment')
file = models.FileField(blank=True,null=True,upload_to='attachments/')
class Comment(models.Model):
ticket = models.ForeignKey(Ticket,related_name='Comment')
comment = models.TextField(null=False)
#your query
from django.db.models import Prefetch
tickets = Ticket.objects.prefetch_related(Prefetch('attachment',to_attr='ticket_attachment'),Prefetch('comment',to_attr='ticket_comment'))
print(ticket.first().ticket_attachment.all())