0

I want to insert data from Excel into SQL Server. I have written code but the values are not being read from Excel:

System.Data.DataTable dt = new System.Data.DataTable();                

Workbook WB = Globals.ThisAddIn.Application.ActiveWorkbook;    
Sheets worksheets = WB.Worksheets;    
lastrow = WB.ActiveSheet.UsedRange.Rows.Count;                         

for(int i = 2; i<= lastrow; i++)      
{    
     cmd.CommandText = ("INSERT Table_1 (emp_no,emp_name,salary) values (WB.Cells[i , 1] , WB.Cells[i , 2] , WB.Cells[i , 3]))");                    
}    
3
  • How about INSERT INTO Table_1 ...? Commented Apr 26, 2018 at 14:36
  • checked itz not working.. and tried by adding '"&WB.cells[i,1]&"' also not working. Commented Apr 26, 2018 at 14:46
  • 2
    SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection - check out Little Bobby Tables Commented Apr 26, 2018 at 14:48

1 Answer 1

2

Strongly not recommended, but working solution:

for(int i = 2; I <= lastrow; i++)      
{    
    cmd.CommandText = ($"INSERT INTO Table_1 (emp_no,emp_name,salary) VALUES ({WB.Cells[i, 1]}, {WB.Cells[i, 2]}, {WB.Cells[i, 3]}))");                    
}    

Please don't use this and read about SQL injection for why not to use it!

Do yourself a favor and use parametrized queries instead.

Sign up to request clarification or add additional context in comments.

2 Comments

For future reference... does the $ mean that you can use code variables inside text?
Yes, kind of, it's the string interpolation operator, which allows for use of C# code inside of the the {} in the string. further reading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.