在docker容器上执行SQL脚本

时间:2016-01-14 00:56:02

标签: mysql docker

我有一个运行mysql的docker容器,我想将.sql文件推送到容器,然后让mysql执行其中的命令。第一步非常简单:

docker cp ./dummy.sql <container_id>:/

从那里我试图从命令行运行mysql并将其指向我刚刚推送到容器的文件。

docker exec <container_id> mysql -u root -ppassword < /dummy.sql

这个命令似乎试图在本地使用/sample.sql作为stdin,而不是在容器上。我还尝试在容器ID之后包装所有内容的引号,这似乎也不起作用。

我也尝试将带有命令的.sh文件推送到docker容器,然后执行它,但这不太理想,也无法正常工作。有什么建议吗?

3 个答案:

答案 0 :(得分:8)

如果要在命令中执行管道重定向,请将其作为字符串传递给/bin/sh

docker exec <container_id> /bin/sh -c 'mysql -u root -ppassword </dummy.sql'

答案 1 :(得分:2)

首先不需要复制脚本。在努力运行我自己的脚本后,我设法在linux上使用:

执行它

import sys from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg import random class TestClass(QtGui.QMainWindow): ##################################################### def __init__(self): super(TestClass, self).__init__() self.initUI() #################################################### # GUI construction def initUI(self): self.setWindowTitle("Mouse Point, x & y") win = QtGui.QWidget() # creates plot self.plot = pg.PlotWidget() self.plot.setLabel('left', "B", units='T') self.plot.setLabel('bottom', "t", units='s') self.plot.showGrid(x=1, y=1, alpha=None) self.setCentralWidget(win) self.setGeometry(600, 600, 600, 600) self.setWindowTitle('Mouse Point, x& y GUI') # Create some widgets to be placed inside btnRandon = QtGui.QPushButton('Random Function') # Create a grid layout to manage the widgets size and position layout = QtGui.QGridLayout(win) # Add widgets to the layout in their proper positions layout.addWidget(btnRandon, 0, 0) # button to show or hide the OldB layout.addWidget(self.plot, 1, 0) mypen = pg.mkPen('y', width=1) self.curve = self.plot.plot(x=[], y=[], pen=mypen) # Plot self.t_plot_max = 30 self.fe = 10e3 self.t = np.arange(-1 * self.t_plot_max, 0, 1.0 / self.fe) self.len_signal = len(self.t) self.signal = np.zeros(self.len_signal, dtype=np.double) btnRandon.clicked.connect(self.buttonRandomClicked) self.curve.scene().sigMouseMoved.connect(self.onMouseMoved) def onMouseMoved(self, point): p = self.plot.plotItem.vb.mapSceneToView(point) self.statusBar().showMessage("{}-{}".format(p.x(), p.y())) def buttonRandomClicked(self): print ("Show/Hide OldB") self.signal = np.random.rand(20) self.curve.setData(self.signal) # MAIN ################################################## def main(): app = QtGui.QApplication(sys.argv) ex = TestClass() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()

或者如果脚本中包含Use db指令:

docker exec -it <container_name> mysql -u root -ppassword -e "Use mydb; $(cat /path/to/script.sql)"

答案 2 :(得分:1)

尝试:

docker exec <container_id> 'mysql -u root -ppassword </dummy.sql'